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

DatabaseSessionService on PostgreSQL reloads events with equal timestamps out of append order

Open TomShlaim opened this issue 3 weeks ago • 6 comments

🔴 Required Information

DatabaseSessionService.get_session sorts events by timestamp DESC, id DESC (sessions/database_session_service.py:791-793). Event ids are random, so when several events share a timestamp, which happens whenever they are appended within one clock tick, the reload order is a shuffle of the append order. The comment above the sort (:787-790) says the id tie-break makes the order stable; it does, but stable is not chronological.

Workflow resume rebuilds the run from the reloaded events, so a swapped pair can make a replayed node wait on a sibling that already finished (Replay divergence detected). #7286 reported this for both backends. Its SQLite half was fixed by breaking ties on rowid (sqlite_session_service.py:347, commit f33343f); the issue was then closed on 2026-10-14, and the reporter's follow-up that the database cases still fail on main got no answer. This report covers the PostgreSQL half only.

Steps to Reproduce:

  1. Start PostgreSQL 16 and pip install "google-adk[db]==2.14.0" asyncpg.
  2. Run the script below with the PostgreSQL URL. It appends eight events with the same timestamp to one session, on PostgreSQL and on SQLite, then reloads each session with get_session.

Expected Behavior:

Both backends reload the events in append order, ['1', ..., '8'].

Observed Behavior:

google-adk 2.14.0
postgresql: appended ['1', '2', '3', '4', '5', '6', '7', '8']
postgresql: reloaded ['7', '3', '5', '8', '2', '1', '4', '6']
sqlite    : appended ['1', '2', '3', '4', '5', '6', '7', '8']
sqlite    : reloaded ['1', '2', '3', '4', '5', '6', '7', '8']

The PostgreSQL order follows the random ids and changes from run to run.

Environment Details:

  • ADK Library Version (pip show google-adk): 2.14.0 (same sort in 2.11.0 through 2.13.0)
  • Desktop OS: macOS 15 host, PostgreSQL 16.13 in a Linux container
  • Python Version (python -V): Python 3.12.8

Model Information:

  • Are you using LiteLLM: No
  • Which model is being used: N/A (no model; session service only)

🟡 Optional Information

Regression: No. Before 2.10.0 the sort had no tie-break at all; 2.10.0 added id DESC (commit a00a2a977), which made the order stable but not chronological.

Logs: See Observed Behavior.

Screenshots / Video: N/A

Additional Context: Suggested fix: a monotonically increasing column on events (a bigserial sequence, or a per-session counter assigned in append_event) as the tie-break, added to the composite index; SQLite's rowid already plays that role. #7695 (fixed in 2.14.0) changes when a model response gets its timestamp, which narrows the window but leaves ties unordered.

Minimal Reproduction Code:

import asyncio
import sys
import tempfile
import time
from pathlib import Path

import google.adk
from google.adk.events import Event
from google.adk.sessions import DatabaseSessionService
from google.adk.sessions.sqlite_session_service import SqliteSessionService
from google.genai import types

N = 8


async def run(label, service):
    session = await service.create_session(app_name="repro", user_id="u")
    stamp = time.time()
    for i in range(1, N + 1):
        content = types.Content(role="model", parts=[types.Part(text=str(i))])
        await service.append_event(session, Event(author="agent", timestamp=stamp, content=content))
    reloaded = await service.get_session(app_name="repro", user_id="u", session_id=session.id)
    print(f"{label}: appended {[str(i) for i in range(1, N + 1)]}")
    print(f"{label}: reloaded {[e.content.parts[0].text for e in reloaded.events]}")


async def main():
    print("google-adk", google.adk.__version__)
    await run("postgresql", DatabaseSessionService(sys.argv[1]))
    await run("sqlite    ", SqliteSessionService(str(Path(tempfile.mkdtemp()) / "sessions.db")))


asyncio.run(main())

Run as python repro.py "postgresql+asyncpg://<user>:<password>@localhost:5432/<db>".

How often has this issue occurred?: Always, whenever two events share a timestamp.

TomShlaim avatar Nov 09 '26 11:11 TomShlaim

Thanks for the detailed reproduction @TomShlaim!

Since event.id is a random UUID, sorting by id DESC when timestamps are identical causes events to reload out of order on PostgreSQL and other relational databases.

Because fixing this affects database tables and indexes across multiple database backends, I'd like to check with the maintainers on which approach is preferred:

  1. Add a sequential column: Add an auto-incrementing integer/sequence column to the events table to break ties (similar to SQLite's rowid).
  2. Add a per-session counter: Keep a simple incremental counter for events within each session during append_event.

Once the team shares the preferred direction, I would be happy to work on this and submit a PR with tests!

mohitdixit02 avatar Nov 09 '26 19:11 mohitdixit02

Hello @mohitdixit02

Thanks for digging into this, per-session counter seems like a better approach. Events in a session are already saved one at a time, so it is safe and avoids database specific auto increment quirks. Feel free to open a PR. Please cover existing databases (migration) and add a test where several events share the same timestamp.

Hello @TomShlaim,

Could you please share your inputs as well?

llalitkumarrr avatar Nov 13 '26 03:11 llalitkumarrr

Hi @llalitkumarrr @mohitdixit02!

The per-session counter is the right direction for us too, just need to make sure that the migration SQL is in the release notes and that two replicas writing to the same session can't get the same index.

Also, maybe we should do the same thing for SQLite for consistency?

TomShlaim avatar Nov 15 '26 08:11 TomShlaim

Hi @TomShlaim,

Thanks for the feedback! I've opened PR #8124 to implement this. To answer your points:

  1. Replica Concurrency: In DatabaseSessionService.append_event, ADK executes SELECT ... FOR UPDATE on the parent session row (sessions table) on PostgreSQL, MySQL, and MariaDB. This serializes concurrent appends to the same session across replicas so they cannot race or read the same event_index.
  2. SQLite Consistency:
    • SqliteSessionService already uses SQLite's internal monotonic counter (ORDER BY timestamp DESC, rowid DESC), which is why it didn't suffer from this bug.
    • For DatabaseSessionService running on SQLite (sqlite+aiosqlite), PR #8124 adds and migrates event_index as well.
  3. Migration SQL: PR #8124 automatically migrates existing V1 tables on startup via _ensure_schema_columns_exist, but for DBAs applying changes out-of-band, the migration SQL is:
    -- PostgreSQL / SQLite:
    ALTER TABLE events ADD COLUMN event_index INTEGER DEFAULT 0 NOT NULL;
    
    -- MySQL / MariaDB:
    ALTER TABLE events ADD COLUMN event_index INT DEFAULT 0 NOT NULL;
    
    I've also included the SQL in the PR #8124 description for release notes.

mohitdixit02 avatar Nov 15 '26 19:11 mohitdixit02

Thanks @mohitdixit02 , that covers it. One optional thought - SqliteSessionService could move to event_index too, so both services order events the same way. Not a blocker tough IMI

TomShlaim avatar Nov 16 '26 07:11 TomShlaim

Thanks @TomShlaim!

Regarding SqliteSessionService: because SQLite already provides rowid natively, using ORDER BY timestamp DESC, rowid DESC achieves the exact same FIFO reload order without the overhead of computing max(event_index) on each append.

I'll keep PR #8124 focused on fixing DatabaseSessionService, and if the maintainers want to unify the schema across both services for architectural symmetry, we can definitely track that!

mohitdixit02 avatar Nov 16 '26 08:11 mohitdixit02