fix: handle non-serializable types in persistent session event storage#4741
fix: handle non-serializable types in persistent session event storage#4741atian8179 wants to merge 1 commit intogoogle:mainfrom
Conversation
When using DatabaseSessionService or SqliteSessionService, events containing non-serializable objects (e.g., function references from MCP tools) cause PydanticSerializationError during model_dump(). Add fallback parameter to model_dump()/model_dump_json() calls in session storage schemas to gracefully handle unknown types by converting them to descriptive placeholder strings. Fixes google#4724
|
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 ChangesHello, 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 issue where persistent session services would crash when attempting to serialize events containing non-serializable Python objects, such as function references. By introducing a Pydantic 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.
Code Review
This pull request effectively resolves the PydanticSerializationError by using a fallback function during JSON serialization, which is a robust solution. The changes are correctly applied in both DatabaseSessionService and SqliteSessionService contexts. The addition of dedicated unit tests is excellent, ensuring the fix is correct and preventing future regressions. I have a couple of suggestions to improve code maintainability and clarity.
| event_data=event.model_dump( | ||
| exclude_none=True, | ||
| mode="json", | ||
| fallback=lambda v: f"<non-serializable: {type(v).__name__}>", |
There was a problem hiding this comment.
This lambda function is also used in sqlite_session_service.py. To avoid duplication and improve maintainability, consider defining it as a constant in a shared location, for example in src/google/adk/sessions/schemas/shared.py:
# In src/google/adk/sessions/schemas/shared.py
JSON_ENCODER_FALLBACK = lambda v: f"<non-serializable: {type(v).__name__}>"You can then import and use this constant here and in sqlite_session_service.py.
| event.model_dump_json(exclude_none=True), | ||
| event.model_dump_json( | ||
| exclude_none=True, | ||
| fallback=lambda v: f"<non-serializable: {type(v).__name__}>", |
There was a problem hiding this comment.
This lambda function is a duplicate of the one in src/google/adk/sessions/schemas/v1.py. To adhere to the DRY (Don't Repeat Yourself) principle, it would be best to define this as a shared constant and reuse it in both places. This will make future changes to the serialization fallback logic easier to manage.
| assert storage.event_data is not None | ||
| # The function should be serialized as a placeholder string | ||
| actions = storage.event_data.get("actions", {}) | ||
| state_delta = actions.get("state_delta", actions.get("stateDelta", {})) |
There was a problem hiding this comment.
The Event model is configured to use camelCase aliases for JSON serialization (alias_generator=alias_generators.to_camel). This means state_delta will be serialized as stateDelta. The current code checks for state_delta first, which will always be a miss, before falling back to stateDelta. For clarity and to accurately reflect the expected data structure, it's better to access stateDelta directly.
| state_delta = actions.get("state_delta", actions.get("stateDelta", {})) | |
| state_delta = actions.get("stateDelta", {}) |
Problem
DatabaseSessionServiceandSqliteSessionServicecrash withPydanticSerializationErrorwhen events contain non-serializable objects (e.g., function references attached by MCP tools during tool resolution).This affects all agents using persistent session services with tools (severity: high).
Root Cause
StorageEvent.from_event()callsevent.model_dump(exclude_none=True, mode="json")without afallbackparameter. When the Runner attaches non-serializable function objects to events before callingappend_event(), Pydantic cannot serialize them and crashes.InMemorySessionServiceis unaffected because it never serializes events.Solution
Add Pydantic v2's
fallbackparameter tomodel_dump()/model_dump_json()calls in:schemas/v1.py:StorageEvent.from_event()sqlite_session_service.py:append_event()The fallback converts non-serializable types to descriptive placeholder strings (
<non-serializable: function>) instead of crashing. This preserves all serializable data while gracefully degrading for unknown types.Testing
Added
tests/unittests/sessions/test_storage_event_serialization.pywith 3 tests:DatabaseSessionService.append_eventcrashes withPydanticSerializationError: Unable to serialize unknown type: <class 'function'>#4724)All tests pass.
Fixes #4724