fix(sessions): fix httpx client closure during event pagination
fix(sessions): move event iteration inside api_client context in get_session
Move event iteration inside the api_client context manager in VertexAiSessionService.get_session() to prevent client closure during multi-page event fetching.
Please ensure you have read the contribution guide before creating a pull request.
Link to Issue or Description of Change
1. Link to an existing issue (if applicable):
- Closes: #3757
2. Or, if no issue exists, describe the change:
Problem:
When a session contains more than 100 events (requiring pagination), VertexAiSessionService.get_session() fails with:
RuntimeError: Cannot send a request, as the client has been closed.
The root cause is that the events_iterator is consumed outside the async with self._get_api_client() as api_client: context block. When the iterator needs to fetch page 2, 3, etc., the API client has already been closed because the async with block has exited.
# Current buggy flow:
async with self._get_api_client() as api_client:
get_session_response, events_iterator = await asyncio.gather(...)
# ← Client closed here
async for event in events_iterator: # ← Fails on page 2+ (client closed)
session.events.append(...)
Solution:
Move the session creation, user validation, and event iteration inside the async with block so the API client remains open during the entire pagination process:
async with self._get_api_client() as api_client:
get_session_response, events_iterator = await asyncio.gather(...)
# Validation and session creation...
async for event in events_iterator: # ← Now works for all pages
session.events.append(...)
# Client closed after all events are fetched
Testing Plan
Unit Tests:
- [x] I have added or updated unit tests for my change.
- [x] All unit tests pass locally.
pytest tests/unittests/sessions/test_vertex_ai_session_service.py -v
Added regression test: test_get_session_pagination_keeps_client_open
- Creates a
MockAsyncClientWithPaginationthat tracks whether it's inside theasync withcontext - Raises
RuntimeErrorif iteration happens outside the context (matching real httpx behavior) - Simulates 3 pages of events (100 + 100 + 50 = 250 events)
- Verifies all 250 events are successfully retrieved
Manual End-to-End (E2E) Tests:
- Deploy an ADK agent to Vertex AI Agent Engine
- Create a session and send 100+ messages to accumulate >100 events
- Verify
get_session()successfully retrieves all events without error
Before fix:
RuntimeError: Cannot send a request, as the client has been closed.
After fix:
- Session with 201 events (3 pages) loads successfully
- All events are retrieved and appended to the session
Checklist
- [x] I have read the CONTRIBUTING.md document.
- [x] I have performed a self-review of my own code.
- [x] I have commented my code, particularly in hard-to-understand areas.
- [x] I have added tests that prove my fix is effective or that my feature works.
- [x] New and existing unit tests pass locally with my changes.
- [x] I have manually tested my changes end-to-end.
- [x] Any dependent changes have been merged and published in downstream modules.
Additional context
This bug affects any production deployment where users have extended conversations. Sessions accumulating >100 events (which triggers pagination) become completely unusable as the agent cannot load the session to process new messages.
The fix is minimal and maintains backward compatibility - it only changes the scope of the async with block without altering any logic or return values.
Affected versions: Tested on google-adk 1.19.0, but the bug exists in earlier versions as well.
Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).
View this failed invocation of the CLA check for more information.
For the most up to date status, view the checks section at the bottom of the pull request.
Summary of Changes
Hello @AlexisMarasigan, I'm Gemini Code Assist[^1]! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request addresses a critical bug where the httpx client could be prematurely closed during the pagination of events in the VertexAiSessionService. By adjusting the scope of event processing to occur within the client's context manager, it guarantees that all events are successfully retrieved before the client is disposed, preventing data loss and ensuring robust session handling during multi-page event fetching.
Highlights
- Client Closure Fix: The
httpxclient closure issue during multi-page event fetching has been resolved by ensuring that event iteration occurs within theapi_clientcontext manager. - Code Structure Refinement: The logic for validating session ownership, creating the session object, and appending events has been re-indented to be part of the
api_client's scope inVertexAiSessionService.get_session().
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in pull request comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with :thumbsup: and :thumbsdown: on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
[^1]: Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.
Response from ADK Triaging Agent
Hello @AlexisMarasigan, thank you for creating this PR!
Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).
In addition, could you please fill out the "Testing Plan" section in your PR? This information will help reviewers to review your PR more efficiently. Thanks!
Response from ADK Triaging Agent
Hello @AlexisMarasigan, thank you for updating the PR!
Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).
This information will help reviewers to review your PR more efficiently. Thanks!
/gemini review
Hi @AlexisMarasigan , Thank you for your contribution! We appreciate you taking the time to submit this pull request. Can you please fix the lint errors before we can proceed with the review. You can use autoformat.sh to fix them.
@ryanaiagent Gotcha, I'm on it