Skip to content

Conversation

@AlexisMarasigan
Copy link

@AlexisMarasigan AlexisMarasigan commented Nov 29, 2025

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):

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:

  • I have added or updated unit tests for my change.
  • 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 MockAsyncClientWithPagination that tracks whether it's inside the async with context
  • Raises RuntimeError if 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:

  1. Deploy an ADK agent to Vertex AI Agent Engine
  2. Create a session and send 100+ messages to accumulate >100 events
  3. 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

  • I have read the CONTRIBUTING.md document.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have added tests that prove my fix is effective or that my feature works.
  • New and existing unit tests pass locally with my changes.
  • I have manually tested my changes end-to-end.
  • 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.

Move event iteration inside the api_client context manager in
VertexAiSessionService.get_session() to prevent client closure
during multi-page event fetching.
@google-cla
Copy link

google-cla bot commented Nov 29, 2025

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.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @AlexisMarasigan, I'm Gemini Code Assist1! 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 httpx client closure issue during multi-page event fetching has been resolved by ensuring that event iteration occurs within the api_client context 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 in VertexAiSessionService.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 👍 and 👎 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.

Footnotes

  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.

@adk-bot
Copy link
Collaborator

adk-bot commented Nov 29, 2025

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!

@adk-bot adk-bot added the services [Component] This issue is related to runtime services, e.g. sessions, memory, artifacts, etc label Nov 29, 2025
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request addresses a bug in VertexAiSessionService.get_session where the HTTP client was being closed prematurely during event pagination. The fix correctly moves the event iteration logic into the api_client context manager, ensuring the client remains open while iterating through paginated events. The change is correct and effectively resolves the issue. I have added one comment suggesting the addition of a regression test to prevent this issue from recurring, as the current tests do not appear to cover this specific pagination failure scenario.

@adk-bot
Copy link
Collaborator

adk-bot commented Nov 29, 2025

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!

Add test_get_session_pagination_keeps_client_open to verify that
get_session() keeps the API client open while iterating through
paginated events. The test uses a mock client that tracks context
state and raises RuntimeError if iteration occurs outside the
async with block, matching real httpx behavior.
@AlexisMarasigan
Copy link
Author

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request effectively resolves a critical bug where the httpx client was being closed prematurely during event pagination in VertexAiSessionService.get_session(). The fix, which involves moving the event iteration logic inside the api_client context manager, is correct and well-targeted. The addition of the test_get_session_pagination_keeps_client_open regression test is particularly commendable, as it accurately simulates the failure condition using the MockAsyncClientWithPagination class, ensuring the fix is robust and preventing future regressions. The changes are of high quality and I have no further suggestions.

@ryanaiagent ryanaiagent self-assigned this Nov 30, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

services [Component] This issue is related to runtime services, e.g. sessions, memory, artifacts, etc

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] VertexAiSessionService.get_session() fails with httpx client closure during event pagination (>100 events)

3 participants