-
Notifications
You must be signed in to change notification settings - Fork 2.9k
feat: add FirestoreSessionService for serverless session persistence #4439
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
Summary of ChangesHello @anmolg1997, 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 the need for a robust, serverless session persistence solution within the Google ADK for GCP environments. It introduces a new Highlights
🧠 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
Activity
Using Gemini Code AssistThe 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
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 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
|
There was a problem hiding this 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 introduces a FirestoreSessionService for serverless session persistence, which is a great addition for GCP deployments. The implementation is solid and includes comprehensive unit tests. My review focuses on improving performance and ensuring data consistency under concurrent operations. I've identified several areas where database access can be optimized (e.g., using server-side limits, avoiding N+1 queries, and reducing redundant reads) and have pointed out critical race conditions in state updates that should be addressed by using Firestore transactions.
| if app_state_delta: | ||
| current_app_state = await self._get_app_state(app_name) | ||
| current_app_state.update(app_state_delta) | ||
| await self._set_app_state(app_name, current_app_state) | ||
|
|
||
| if user_state_delta: | ||
| current_user_state = await self._get_user_state(app_name, user_id) | ||
| current_user_state.update(user_state_delta) | ||
| await self._set_user_state(app_name, user_id, current_user_state) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The updates to app and user state follow a non-atomic read-modify-write pattern. If multiple sessions are created concurrently for the same app or user, this can lead to race conditions and data loss, as one update may overwrite another. To ensure atomicity and data consistency, these state updates should be performed within a Firestore transaction.
| app_state = await self._get_app_state(app_name) | ||
| user_state = await self._get_user_state(app_name, suid) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fetching app and user state inside the loop is inefficient and causes an N+1 query problem.
- App State:
_get_app_stateshould be called once before the loop, as theapp_nameis constant. - User State: If
user_idis provided tolist_sessions,_get_user_stateshould also be called once before the loop. Ifuser_idisNone, it needs to remain in the loop.
This refactoring will significantly improve performance by reducing database calls.
| if app_state_delta: | ||
| current_app_state = await self._get_app_state(app_name) | ||
| current_app_state.update(app_state_delta) | ||
| await self._set_app_state(app_name, current_app_state) | ||
|
|
||
| if user_state_delta: | ||
| current_user_state = await self._get_user_state( | ||
| app_name, user_id | ||
| ) | ||
| current_user_state.update(user_state_delta) | ||
| await self._set_user_state(app_name, user_id, current_user_state) | ||
|
|
||
| if session_state_delta: | ||
| stored_data = doc.to_dict() | ||
| stored_state = stored_data.get(_FIELD_STATE, {}) | ||
| stored_state.update(session_state_delta) | ||
| await session_ref.update({_FIELD_STATE: stored_state}) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The updates to app, user, and session states are performed using a non-atomic read-modify-write pattern. In a concurrent environment, this can lead to race conditions where state updates from one event overwrite another, causing data loss. For example, if two append_event calls run simultaneously for the same app, they might read the same initial app state, and the last one to write will win, discarding the other's changes.
To ensure data consistency, these state updates should be wrapped in a Firestore transaction. Transactions guarantee that the series of operations (read, modify, write) is atomic.
| app_state = await self._get_app_state(app_name) | ||
| user_state = await self._get_user_state(app_name, user_id) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The code re-fetches the app and user states from Firestore to build the response, even though they might have been fetched and updated just lines before. This can lead to redundant database reads.
To optimize, you could fetch the state at the beginning of the method, apply deltas if they exist, and then reuse the in-memory state for building the response. This would avoid the second read.
| if config and config.num_recent_events: | ||
| events = events[-config.num_recent_events :] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fetching all events and then slicing on the client-side is inefficient, especially for sessions with a long history. It results in unnecessary data transfer and client-side processing.
To optimize this, you should use a server-side limit. The google-cloud-firestore client supports limit_to_last() which can be applied to the query. This will fetch only the required number of recent events from Firestore.
Example:
if config and config.num_recent_events:
events_query = events_query.limit_to_last(config.num_recent_events)
event_docs = events_query.stream()
# ... process docs ...
# Then this client-side slicing can be removed.| events_ref = session_ref.collection(_EVENTS_SUBCOLLECTION) | ||
| async for event_doc in events_ref.stream(): | ||
| await event_doc.reference.delete() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Deleting event documents one by one within a loop is inefficient, as each .delete() call results in a separate network request. For sessions with a large number of events, this can be slow and could potentially exceed rate limits.
A more performant approach is to use a batch write to delete multiple documents in a single request. You can use AsyncWriteBatch from the Firestore client to collect all delete operations and commit them at once.
Adds a new session service backed by Google Cloud Firestore, providing persistent, serverless session storage. This addresses the gap between InMemorySessionService (dev-only) and DatabaseSessionService (requires managing SQL infrastructure) for GCP-native deployments. The implementation follows established ADK patterns: - Extends BaseSessionService with all CRUD operations - Supports three-tier state management (app/user/session) - Events stored in Firestore subcollections (avoids 1MB doc limit) - Lazy import via __getattr__ (same pattern as DatabaseSessionService) - google-cloud-firestore added as optional 'firestore' extra Ref: google#3776 Co-authored-by: Cursor <cursoragent@cursor.com>
1edbca4 to
368a6fc
Compare
Link to Issue or Description of Change
Problem:
The ADK currently lacks a serverless, low-infrastructure session backend for GCP deployments.
InMemorySessionServiceis dev-only,DatabaseSessionServicerequires SQL infrastructure, andVertexAiSessionServicerequires a Reasoning Engine.Solution:
Adds
FirestoreSessionService— a newBaseSessionServiceimplementation backed by Google Cloud Firestore. This provides persistent, serverless session storage with zero database management.Key design decisions:
__getattr__(same pattern asDatabaseSessionService)google-cloud-firestoreadded as optionalfirestoreextraTesting Plan
Unit Tests:
17 new unit tests covering all CRUD operations, state management, event handling, and edge cases. Firestore interactions are mocked (no GCP project needed).
Manual E2E Tests:
Requires a GCP project with Firestore enabled. Set up ADC and instantiate: