From 4367fd94d9c29814b9ee7806652ee4827977ac46 Mon Sep 17 00:00:00 2001 From: chelsealong Date: Fri, 25 Sep 2026 12:15:46 +0000 Subject: [PATCH] fix(sessions): preserve append order for tied timestamps in SqliteSessionService SqliteSessionService.get_session broke timestamp ties with `ORDER BY id DESC`. Event ids are random, so tied events come back in an order unrelated to how they were appended, reshuffling a replayed conversation and, for a resumable Workflow, handing ReplayManager a completion order it can never reproduce. Break ties on `rowid` instead, which reflects actual insertion order. Fixes #7286 for SqliteSessionService. DatabaseSessionService has the same class of bug but needs a portable insertion-order column across SQLite and Postgres, which is a larger schema/migration change left for a follow-up. --- .../adk/sessions/sqlite_session_service.py | 10 ++-- .../sessions/test_session_service.py | 52 ++++++++++++++++--- 2 files changed, 50 insertions(+), 12 deletions(-) diff --git a/src/google/adk/sessions/sqlite_session_service.py b/src/google/adk/sessions/sqlite_session_service.py index 262d8149a0c..77c5e5d670f 100644 --- a/src/google/adk/sessions/sqlite_session_service.py +++ b/src/google/adk/sessions/sqlite_session_service.py @@ -308,10 +308,12 @@ async def get_session( query_parts.append("AND timestamp >= ?") params.append(config.after_timestamp) - # Break timestamp ties on id so tied events come back in the same order - # on every read; otherwise a replayed conversation shuffles and - # `num_recent_events` truncates at an arbitrary point in the tie. - query_parts.append("ORDER BY timestamp DESC, id DESC") + # Break timestamp ties on rowid, which reflects insertion order, rather + # than on the event's random id. Ordering by id would come back in an + # order unrelated to how the events were appended, which reshuffles a + # replayed conversation and, for `Workflow`, breaks resume by handing + # `ReplayManager` a completion order it can never reproduce. + query_parts.append("ORDER BY timestamp DESC, rowid DESC") if config and config.num_recent_events is not None: query_parts.append("LIMIT ?") diff --git a/tests/unittests/sessions/test_session_service.py b/tests/unittests/sessions/test_session_service.py index e59b9376870..b926fa0153d 100644 --- a/tests/unittests/sessions/test_session_service.py +++ b/tests/unittests/sessions/test_session_service.py @@ -3242,27 +3242,29 @@ async def test_get_session_keeps_exact_epoch_across_a_repeated_local_hour( @pytest.mark.asyncio -@pytest.mark.parametrize( - 'service_type', [SessionServiceType.DATABASE, SessionServiceType.SQLITE] -) @pytest.mark.parametrize('append_ids_in_reverse', [False, True]) async def test_get_session_orders_tied_timestamps_by_id( - service_type, append_ids_in_reverse, tmp_path + append_ids_in_reverse, tmp_path ): - """Events sharing a timestamp come back in a stable, id-ordered sequence. + """DatabaseSessionService breaks tied timestamps by id, not append order. Without a tiebreaker the database is free to return tied events in any order, so a replayed conversation shuffles between fetches and `num_recent_events` truncates at an arbitrary point inside the tie. Ordering on id as well also keeps the last returned event consistent with the event the stale-session check treats as the latest one. + + This documents current `DatabaseSessionService` behavior; it is not the + same as append order (see + `test_sqlite_session_service_preserves_append_order_on_tied_timestamps`), + which is a known limitation tracked separately. """ app_name = 'my_app' user_id = 'user' event_ids = ['event_a', 'event_m', 'event_z'] shared_timestamp = 100.0 - service = get_session_service(service_type, tmp_path) + service = get_session_service(SessionServiceType.DATABASE, tmp_path) try: session = await service.create_session(app_name=app_name, user_id=user_id) append_order = ( @@ -3278,12 +3280,46 @@ async def test_get_session_orders_tied_timestamps_by_id( app_name=app_name, user_id=user_id, session_id=session.id ) finally: - if isinstance(service, DatabaseSessionService): - await service.close() + await service.close() assert [event.id for event in retrieved_session.events] == event_ids +@pytest.mark.asyncio +@pytest.mark.parametrize('append_ids_in_reverse', [False, True]) +async def test_sqlite_session_service_preserves_append_order_on_tied_timestamps( + append_ids_in_reverse, tmp_path +): + """SqliteSessionService returns tied-timestamp events in append order. + + Event ids are random, so a tiebreaker on id comes back in an order + unrelated to how the events were appended. For a resumable `Workflow`, + `ReplayManager` builds its replay barrier from this reloaded order, so a + swapped pair makes resume fail after the barrier timeout. + """ + app_name = 'my_app' + user_id = 'user' + event_ids = ['event_a', 'event_m', 'event_z'] + shared_timestamp = 100.0 + + service = get_session_service(SessionServiceType.SQLITE, tmp_path) + session = await service.create_session(app_name=app_name, user_id=user_id) + append_order = ( + list(reversed(event_ids)) if append_ids_in_reverse else event_ids + ) + for event_id in append_order: + await service.append_event( + session, + Event(author='user', id=event_id, timestamp=shared_timestamp), + ) + + retrieved_session = await service.get_session( + app_name=app_name, user_id=user_id, session_id=session.id + ) + + assert [event.id for event in retrieved_session.events] == append_order + + def test_delete_session_sync_removes_only_the_targeted_users_session(): """Deleting is scoped to one (app, user, session) triple.""" service = InMemorySessionService()