Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions src/google/adk/sessions/sqlite_session_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ?")
Expand Down
52 changes: 44 additions & 8 deletions tests/unittests/sessions/test_session_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = (
Expand All @@ -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()
Expand Down
Loading