adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

DatabaseSessionService raises false StaleSessionError when two events share a timestamp

Open rishwanth-th opened this issue 2 months ago • 4 comments

🔴 Required Information

Describe the Bug:

DatabaseSessionService.append_event raises StaleSessionError ("The session has been modified in storage since it was loaded") when there is only one writer. It happens when an event has the same timestamp, to the microsecond, as the previous event and carries a state change.

Cause: append_event sets storage_session.update_time to the event's timestamp, and get_update_marker() (that timestamp in microseconds) is the revision marker for the stale-writer check. The column is also declared onupdate=func.now() (schemas/v1.py, StorageSession.update_time). When the new timestamp equals the stored one, SQLAlchemy sees no change to update_time and leaves it out of the UPDATE. The UPDATE still runs because state changed, so onupdate fires and the database's now() is written instead: whole seconds on SQLite (…:37.000000), the transaction start time on Postgres. The marker kept on the in-memory session (read before commit) no longer matches storage, so the next append_event on that session fails.

Equal timestamps are common with coarse clocks: Python 3.12 on Windows uses GetSystemTimeAsFileTime (15.6 ms by default), so a workflow that emits several events per step hits this in most runs. We hit it running a graph Workflow with RequestInput pause/resume and ResumabilityConfig(is_resumable=True).

This is the documented setup: the sessions page shows DatabaseSessionService(db_url="sqlite+aiosqlite:///./my_agent_data.db") as the persistent-storage example. SqliteSessionService, which does not have the problem, is not mentioned in the docs.

Steps to Reproduce:

  1. pip install "google-adk[db]==2.9.2" (plus asyncpg for Postgres)
  2. Save the script below as repro.py
  3. python repro.py "sqlite+aiosqlite:///./repro.db" or python repro.py "postgresql+asyncpg://user:pass@localhost:5432/db"
  4. The third append_event raises StaleSessionError

Expected Behavior:

Appends from the only writer succeed, whatever the event timestamps.

Observed Behavior:

google.adk.errors._stale_session_error.StaleSessionError: The session has been modified in storage since it was loaded. Please reload the session before appending more events.

The stored update_time after the second append is 2026-09-25T04:37:37.000000 (SQLite) while the session's marker is 2026-09-25T04:37:37.847349.

Environment Details:

  • ADK Library Version: 2.9.2 (also present on main as of 2026-09-25)
  • Desktop OS: Windows 11; the Postgres run also from Linux (Docker)
  • Python Version: 3.12.14
  • SQLAlchemy 2.0.54, aiosqlite 0.22.1, asyncpg 0.31.0, Postgres 17.11

Model Information:

  • Are you using LiteLLM: Yes (not involved in the bug)
  • Which model is being used: Azure OpenAI gpt-5.4 (not involved)

🟡 Optional Information

Minimal Reproduction Code:

import asyncio
import sys
import time

from google.adk.events import Event, EventActions
from google.adk.sessions import DatabaseSessionService


async def main(db_url: str) -> None:
    service = DatabaseSessionService(db_url=db_url)
    session = await service.create_session(app_name="repro", user_id="u")

    ts = time.time()
    await service.append_event(session, Event(author="a", timestamp=ts))
    # Same timestamp as the previous event, with a state change.
    await service.append_event(
        session,
        Event(author="a", timestamp=ts, actions=EventActions(state_delta={"k": 1})),
    )
    # Raises StaleSessionError.
    await service.append_event(session, Event(author="a", timestamp=ts + 1))
    print("no error")


asyncio.run(main(sys.argv[1]))

How often has this issue occurred?:

  • Always (100%) with the script above, on SQLite and Postgres.
  • In a real workflow it depends on the clock. Start + resume cycles of a two-step Workflow, with ADK's clock set to a 15.625 ms tick through google.adk.platform.time.set_time_provider: 92/100 cycles failed on SQLite and 82/100 on Postgres 17. On Linux with a 1 ns clock: 0/300 on Postgres.

Additional Context:

Possible fixes:

  • Drop onupdate=func.now() from update_time: append_event always sets it explicitly, and create_session already has default.
  • Or mark the attribute modified (sqlalchemy.orm.attributes.flag_modified(storage_session, "update_time")) so the explicit value is always written.
  • Document SqliteSessionService for local SQLite use.

User-side workaround: subclass DatabaseSessionService and bump event.timestamp to one microsecond after session.last_update_time when it is not strictly later. The comparison must use datetime.fromtimestamp, as append_event does; comparing round(ts * 1e6) disagrees on half-microsecond floats.

Related but different: #6943 (SQL Server precision), #5085 (MySQL timezone), #3717.

rishwanth-th avatar Sep 25 '26 07:09 rishwanth-th

Picking this one up now — opening a PR shortly. Flagging it here so nobody duplicates the work; if someone is already on it, say so and I will drop mine.

chelsealong avatar Sep 25 '26 07:09 chelsealong

The repro made this quick to confirm @rishwanth-th. Seeing the same StaleSessionError on 2.9.2 and main and it isn't fixed in any release (1.24.0 to 2.2.0 fail on the same input with MissingGreenlet instead).

As a workaround until a fix ships try a SQLAlchemy before_update listener on StorageSession that calls flag_modified(target, "update_time"). That kept the explicit timestamp and the third append went through. Could you check whether that holds up in your Workflow setup especially on Postgres?

@chelsealong ran #7277: the sessions tests pass and the new test fails without the change. But schemas/v0.py still has onupdate=func.now() so databases on the legacy v0 schema still raise. Could you cover v0 too (or use flag_modified in append_event), add a v0 case and test it thoroughly before it goes up for review?

surajksharma07 avatar Sep 25 '26 08:09 surajksharma07

Thanks @surajksharma07. The listener holds up in our Workflow setup, including on Postgres.

Setup: google-adk 2.9.2, SQLAlchemy 2.0.54, asyncpg 0.31.0, Postgres 17.11 in Docker, Python 3.12 on Windows 11. Each cycle runs a resumable Workflow that pauses on RequestInput and is then resumed with a FunctionResponse, all through DatabaseSessionService. "Coarse clock" means ADK's clock set to tick every 15.625 ms (Windows' default timer) via google.adk.platform.time.set_time_provider, which makes the timestamps collide.

Database Clock Without listener With listener
Postgres 17 coarse 75 / 100 0 / 100
Postgres 17 host clock 3 / 100 0 / 100
SQLite (aiosqlite) coarse 84 / 100 0 / 100

Listener as used:

def _keep_update_time(mapper, connection, target):
    flag_modified(target, "update_time")

for model in (v0.StorageSession, v1.StorageSession):
    event.listen(model, "before_update", _keep_update_time)

We've switched to this until a release includes the fix. Note the 3/100 on Postgres with the normal host clock: this isn't only a coarse-clock problem.

rishwanth-th avatar Sep 25 '26 11:09 rishwanth-th

Really useful data @rishwanth-th. The 3/100 on Postgres with the normal host clock shows it isn't only a coarse-clock problem so staying on the listener until a release has the fix makes sense. Main hasn't changed here (still 044a1ec) and your repro still raises StaleSessionError on it.

One more data point for the fix: ADK's own test_append_event_calls_rollback_on_commit_failure flakes on Windows for the same reason (create_session and the first state_delta event land on the same tick). On main it failed 6/20 with a false StaleSessionError. With #7277 or the listener it's 0/20.

@chelsealong #7277 is still at 814ee8e and re-checked on current main it fixes schema v1 but v0 still raises StaleSessionError. Could you cover v0 as well (same change in schemas/v0.py or flag_modified right after the update_time assignment in append_event which covers both) with a v0 test case and re-run the sessions suite before asking for review?

surajksharma07 avatar Sep 28 '26 18:09 surajksharma07