Skip to content

AttributeError in Events Compaction with DatabaseSessionService #3530

Closed

Description

@mendac

Kaggle Day 2 Section 3 - Persistence

Hardware: Raspberry Pi 5, 16GB, Raspberry Pi OS Trixie

Summary

When using EventsCompactionConfig with DatabaseSessionService, the application intermittently crashes with an
AttributeError: 'dict' object has no attribute 'start_timestamp' in _process_compaction_events().
The error occurs because compaction event objects are being serialized/deserialized as dictionaries from the database
but the code expects objects with attribute access.

Environment

  • google-adk version: 1.18.0
  • google-genai version: 1.49.0
  • Python version: 3.13.5
  • Operating System: Linux (Raspberry Pi OS, aarch64)
  • Database: SQLite (via SQLAlchemy)

Steps to Reproduce

  1. Create an app with EventsCompactionConfig enabled
  2. Use DatabaseSessionService with SQLite backend
  3. Run multiple conversation turns (enough to trigger compaction - e.g., 3+ turns with compaction_interval=3)
  4. The error occurs when compaction data exists in the database from a previous run

Minimal reproduction code:

import os
import asyncio
from google.adk.agents import LlmAgent
from google.adk.apps.app import App, EventsCompactionConfig
from google.adk.models.google_llm import Gemini
from google.adk.sessions import DatabaseSessionService
from google.adk.runners import Runner
from google.genai import types

# Configure API key
os.environ["GOOGLE_API_KEY"] = "blahblahblah"
os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "FALSE"

# Create agent with compaction
agent = LlmAgent(
    model=Gemini(model="gemini-2.5-flash-lite"),
    name="test_agent",
    description="Day 2 Section 3 compaction bug"
)

# Create app with compaction enabled
app = App(
    name="compaction_bug_test",
    root_agent=agent,
    events_compaction_config=EventsCompactionConfig(
        compaction_interval=3,
        overlap_size=1,
    ),
)

# Use database session service (this is where the bug manifests)
session_service = DatabaseSessionService(db_url="sqlite:///test_compaction.db")
runner = Runner(app=app, session_service=session_service)

async def test():
    session = await session_service.create_session(
        app_name="compaction_bug_test",
        user_id="test_user",
        session_id="test_session"
    )

    # First run works just fine, but...
    for i in range(4):
        query = types.Content(role="user", parts=[types.Part(text=f"Message {i+1}")])
        async for event in runner.run_async(
            user_id="test_user",
            session_id=session.id,
            new_message=query
        ):
            pass

    print("Survived first run - run again to trigger the bug")

asyncio.run(test())

To reproduce the error:

  • Run the script once (works fine)
  • Run it again immediately (persistently crashes with AttributeError)

Expected Behavior

Compaction should work seamlessly with DatabaseSessionService, properly serializing and deserializing compaction event objects across sessions.

Actual Behavior

On subsequent runs when compaction data exists in the database, the application crashes with:

Traceback (most recent call last):
  File "/home/pi/adk/2a3.py", line 135, in <module>
    asyncio.run(main())
  File "/home/pi/adk/2a3.py", line 55, in run_session
    async for event in runner_instance.run_async(
        user_id=USER_ID, session_id=session.id, new_message=query
    ):
  File "/home/pi/AC1/lib/python3.13/site-packages/google/adk/runners.py", line 653, in _exec_with_plugin
    async for event in agen:
      yield (modified_event if modified_event else event)
  File "/home/pi/AC1/lib/python3.13/site-packages/google/adk/flows/llm_flows/contents.py", line 354, in _get_contents
    events_to_process = _process_compaction_events(raw_filtered_events)
  File "/home/pi/AC1/lib/python3.13/site-packages/google/adk/flows/llm_flows/contents.py", line 265, in _process_compaction_events
    compaction.start_timestamp is not None
    ^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'dict' object has no attribute 'start_timestamp'

Root Cause Analysis

The issue is in /google/adk/flows/llm_flows/contents.py at line 265 in _process_compaction_events():

compaction.start_timestamp is not None  # Line 265

The code assumes compaction is an object with attributes, but when retrieved from the database via DatabaseSessionService, it's deserialized as a dictionary. The code should either:

  1. Use dictionary access: compaction.get('start_timestamp') or compaction['start_timestamp']
  2. Properly deserialize compaction events into the expected object type

Impact

This bug completely breaks the persistence feature when using events compaction, critical for me not to lose more hair.

Additional Context

  • The error is predictable because it only occurs when compaction data already exists in the database
  • Fresh database runs work fine on the first execution
  • The issue appears to be a serialization/deserialization mismatch in the session storage layer
  • This affects any production use case requiring persistent sessions with compaction

Requested Fix

In order for me to finish this lab, please ensure compaction event objects are properly serialized/deserialized when using DatabaseSessionService, maintaining attribute access compatibility or updating all access patterns to handle dictionary objects consistently.

Activity

  1. added
    services[Component] This issue is related to runtime services, e.g. sessions, memory, artifacts, etc
    on Nov 13, 2025
  2. added theissue type on Nov 13, 2025
  3. mendac commented on Nov 13, 2025

    @mendac
    Author

    A fuller code snippet:

    import os
    import asyncio
    from google.adk.agents import LlmAgent
    from google.adk.apps.app import App, EventsCompactionConfig
    from google.adk.models.google_llm import Gemini
    from google.adk.sessions import DatabaseSessionService
    from google.adk.runners import Runner
    from google.genai import types

    Configure API key

    GOOGLE_API_KEY = "YOUR_API_KEY_HERE" # Replace with your actual API key
    os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
    os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "FALSE"

    Constants

    USER_ID = "test_user"
    SESSION_ID = "test_session"
    APP_NAME = "compaction_bug_test"
    DB_FILE = "bug_reproduction.db"

    print(f"Starting bug reproduction test...")
    print(f"Database file: {DB_FILE}")

    Create agent

    agent = LlmAgent(
    model=Gemini(model="gemini-2.5-flash-lite"),
    name="test_agent",
    description="Test agent for compaction bug reproduction"
    )

    Create app with compaction enabled

    app = App(
    name=APP_NAME,
    root_agent=agent,
    events_compaction_config=EventsCompactionConfig(
    compaction_interval=3, # Trigger compaction after 3 turns
    overlap_size=1,
    ),
    )

    Use database session service - this is where the bug occurs

    session_service = DatabaseSessionService(db_url=f"sqlite:///{DB_FILE}")
    runner = Runner(app=app, session_service=session_service)

    async def main():
    print(f"\nCreating/retrieving session: {SESSION_ID}")

    try:
        session = await session_service.create_session(
            app_name=APP_NAME,
            user_id=USER_ID,
            session_id=SESSION_ID
        )
    except:
        session = await session_service.get_session(
            app_name=APP_NAME,
            user_id=USER_ID,
            session_id=SESSION_ID
        )
    
    print(f"Session created: {session.id}\n")
    
    # Send 4 messages to trigger compaction (interval=3)
    messages = [
        "Hello, this is message 1",
        "This is message 2",
        "This is message 3",
        "This is message 4 - compaction should have triggered"
    ]
    
    for i, message_text in enumerate(messages, 1):
        print(f"Turn {i}: {message_text}")
    
        query = types.Content(
            role="user",
            parts=[types.Part(text=message_text)]
        )
    
        try:
            async for event in runner.run_async(
                user_id=USER_ID,
                session_id=session.id,
                new_message=query
            ):
                if event.content and event.content.parts:
                    if event.content.parts[0].text:
                        print(f"Agent: {event.content.parts[0].text[:100]}...")
        except AttributeError as e:
            print(f"\n❌ BUG TRIGGERED! AttributeError occurred:")
            print(f"   {e}")
            print(f"\nThis error happens because compaction data from a previous")
            print(f"run is stored as a dict but accessed as an object with attributes.")
            print(f"\nTo reproduce again: Run this script multiple times.")
            print(f"To reset: Delete {DB_FILE}")
            raise
    
    print(f"\n✅ Script completed successfully!")
    print(f"Run this script again to trigger the bug.")
    

    if name == "main":
    asyncio.run(main())

  4. hangfei commented on Nov 14, 2025

    @hangfei
    Collaborator

    thanks for reporting. we are working on a fix. duplicate to #3487.

  5. nengine commented on Dec 23, 2025

    @nengine

    Hello is this fix now included in version 1.21? Thanks.

  6. ryanovas commented on Dec 30, 2025

    @ryanovas
  7. JahangirJadi commented on Jan 1, 2026

    @JahangirJadi

    Facing the same issue in v1.21. It's not fixed yet.

  8. wuliang229 commented on Jan 20, 2026

    @wuliang229
    Collaborator

    Please update to 1.22.1 and try again. The issue should be fixed in the latest version using the JSON-based schema.

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

Metadata

Metadata

Assignees

Labels

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

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions