Skip to content

feat(sessions): add public prepare_tables() for eager initialization#4858

Open
ferponse wants to merge 3 commits intogoogle:mainfrom
ferponse:feat/eager-table-preparation
Open

feat(sessions): add public prepare_tables() for eager initialization#4858
ferponse wants to merge 3 commits intogoogle:mainfrom
ferponse:feat/eager-table-preparation

Conversation

@ferponse
Copy link

@ferponse ferponse commented Mar 17, 2026

Fixes #4857

Summary

  • Rename _prepare_tables() to prepare_tables(), making it part of the public API so applications can eagerly initialize database tables at startup and avoid the latency spike on the first user request.
  • All internal callers (create_session, get_session, list_sessions, delete_session, append_event) updated to call the now-public method. Lazy behavior is fully preserved.
  • Existing tests updated to use the public method name.
  • New test (test_public_prepare_tables_eager_initialization) verifies eager initialization works correctly.

Motivation

In our production application using DatabaseSessionService with PostgreSQL, the first user query after a restart is noticeably slower because _prepare_tables() runs schema detection + metadata.create_all() inline. By making the method public, applications can call it during startup (e.g. in a FastAPI lifespan handler) to eliminate this cold-start penalty:

session_service = DatabaseSessionService(db_url=db_url)
await session_service.prepare_tables()  # eager initialization at startup

Test plan

  • New test test_public_prepare_tables_eager_initialization passes
  • All existing prepare_tables tests still pass (4/4)
  • Fully backward compatible — lazy initialization still works for applications that don't call prepare_tables() explicitly

@google-cla
Copy link

google-cla bot commented Mar 17, 2026

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.

@adk-bot adk-bot added the services [Component] This issue is related to runtime services, e.g. sessions, memory, artifacts, etc label Mar 17, 2026
@adk-bot
Copy link
Collaborator

adk-bot commented Mar 17, 2026

Response from ADK Triaging Agent

Hello @ferponse, thank you for your contribution!

Before we can merge this PR, you'll need to sign the Contributor License Agreement (CLA). You can find more information at https://cla.developers.google.com/.

Thanks!

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, 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 introduces a new public method, prepare_tables(), to the DatabaseSessionService class. This allows applications to eagerly initialize database tables, avoiding performance hits on initial requests after a restart. The change is backward compatible, with a new test case added to validate the new functionality.

Highlights

  • Eager Initialization: Introduced a public prepare_tables() method to DatabaseSessionService for eagerly initializing database tables during application startup, addressing potential latency spikes on the first user request.
  • No Behavioral Change: The new method delegates to the existing _prepare_tables(), ensuring no changes to the lazy initialization path and maintaining backward compatibility.
  • Test Coverage: Added a new test case (test_public_prepare_tables_eager_initialization) to verify the eager initialization functionality and ensure subsequent operations succeed.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • src/google/adk/sessions/database_session_service.py
    • Added prepare_tables() method for eager database table initialization.
  • tests/unittests/sessions/test_session_service.py
    • Added test_public_prepare_tables_eager_initialization to verify eager initialization.
Activity
  • Add a public prepare_tables() method to DatabaseSessionService.
  • Delegate the new method to the existing _prepare_tables().
  • Add a test to verify eager initialization works and subsequent operations succeed.
  • Ensure no changes to the lazy initialization path.
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.

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 adds a public prepare_tables() method to DatabaseSessionService for eager database table initialization, which helps avoid cold-start latency. The change is straightforward and includes a new unit test to validate the functionality. I have one suggestion to improve the new test by using an async with context manager for resource handling, which enhances code clarity and maintains consistency with other tests in the file.

Comment on lines +1189 to +1208
service = DatabaseSessionService('sqlite+aiosqlite:///:memory:')
try:
# Before calling prepare_tables, tables are not created.
assert not service._tables_created
assert service._db_schema_version is None

# Eagerly prepare tables via the public API.
await service.prepare_tables()

# Tables should now be ready.
assert service._tables_created
assert service._db_schema_version is not None

# Subsequent operations should work without any additional setup cost.
session = await service.create_session(
app_name='app', user_id='user', session_id='s1'
)
assert session.id == 's1'
finally:
await service.close()
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

For improved resource management and consistency with other tests in this file (e.g., test_append_event_to_stale_session), it is more idiomatic to use an async with block to manage the DatabaseSessionService instance. This ensures that service.close() is called automatically, even if errors occur, making the code cleaner and safer.

  async with DatabaseSessionService('sqlite+aiosqlite:///:memory:') as service:
    # Before calling prepare_tables, tables are not created.
    assert not service._tables_created
    assert service._db_schema_version is None

    # Eagerly prepare tables via the public API.
    await service.prepare_tables()

    # Tables should now be ready.
    assert service._tables_created
    assert service._db_schema_version is not None

    # Subsequent operations should work without any additional setup cost.
    session = await service.create_session(
        app_name='app', user_id='user', session_id='s1'
    )
    assert session.id == 's1'

Copy link
Author

Choose a reason for hiding this comment

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

Done! Updated in be0f4e2 to use async with context manager. Thanks for the suggestion!

@ferponse ferponse force-pushed the feat/eager-table-preparation branch from eb1eaee to e27aad7 Compare March 17, 2026 11:53
@ferponse
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 makes the _prepare_tables method public by renaming it to prepare_tables, allowing applications to perform eager initialization of database tables. This is a well-motivated change to reduce latency on the first request. All internal callers have been updated, and the lazy-initialization behavior is preserved. The tests have been updated accordingly, and a new test has been added to verify the new functionality. The changes are correct and well-implemented.

@rohityan rohityan self-assigned this Mar 17, 2026
@rohityan rohityan added the request clarification [Status] The maintainer need clarification or more information from the author label Mar 17, 2026
@rohityan
Copy link
Collaborator

Hi @ferponse , Thank you for your contribution! It appears you haven't yet signed the Contributor License Agreement (CLA). Please visit https://cla.developers.google.com/ to complete the signing process. Once the CLA is signed, we'll be able to proceed with the review of your PR. Thank you!

…zation

DatabaseSessionService currently initializes database tables lazily on
the first database operation via a private _prepare_tables() method.
This causes a noticeable latency spike on the first user request.

Rename _prepare_tables() to prepare_tables() so that applications can
call it at startup to pay the table-creation cost upfront. The lazy
behavior is preserved — each public method still calls prepare_tables()
internally.
Address review feedback: use `async with` instead of try/finally for
DatabaseSessionService resource management, consistent with other tests.
@ferponse ferponse force-pushed the feat/eager-table-preparation branch from 0a4b6e5 to dc3b945 Compare March 18, 2026 08:36
@ferponse
Copy link
Author

Hi @rohityan, thanks for the heads up! The CLA should now be signed. Could you re-check when you get a chance? Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

request clarification [Status] The maintainer need clarification or more information from the author 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.

DatabaseSessionService: first query is slow due to lazy table initialization

3 participants