Skip to content

Commit f438025

Browse files
committed
fix(sessions): use INSERT ON CONFLICT DO NOTHING to prevent race in create_session
When multiple concurrent create_session calls target the same app_name on a fresh database, the SELECT-then-INSERT pattern on app_states and user_states tables causes UniqueViolation errors. All concurrent callers see None from the SELECT and all attempt INSERT. Replace the check-then-insert pattern with dialect-specific INSERT ... ON CONFLICT DO NOTHING (PostgreSQL and SQLite). For unsupported dialects, the original get-then-add fallback is preserved. Added regression tests for concurrent session creation with: - Same app_name, different user_ids (app_states race) - Same app_name AND user_id (user_states race) Fixes google#4954
1 parent 4cbc3dc commit f438025

2 files changed

Lines changed: 142 additions & 11 deletions

File tree

‎src/google/adk/sessions/database_session_service.py‎

Lines changed: 77 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@
2828
from sqlalchemy import delete
2929
from sqlalchemy import event
3030
from sqlalchemy import select
31+
from sqlalchemy.dialects.postgresql import insert as pg_insert
32+
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
3133
from sqlalchemy.engine import make_url
3234
from sqlalchemy.exc import ArgumentError
3335
from sqlalchemy.ext.asyncio import async_sessionmaker
@@ -359,6 +361,70 @@ async def _session_matches_storage_revision(
359361
latest_storage_event_id = result.scalar_one_or_none()
360362
return latest_storage_event_id == session.events[-1].id
361363

364+
async def _ensure_state_rows(
365+
self,
366+
*,
367+
sql_session: DatabaseSessionFactory,
368+
schema: _SchemaClasses,
369+
app_name: str,
370+
user_id: str,
371+
) -> None:
372+
"""Ensure app_states and user_states rows exist, creating them atomically.
373+
374+
Uses INSERT ... ON CONFLICT DO NOTHING (PostgreSQL/SQLite) to avoid
375+
UniqueViolation errors when multiple concurrent create_session calls
376+
race to insert the same app_name or (app_name, user_id) row.
377+
"""
378+
dialect_name = self.db_engine.dialect.name
379+
380+
if dialect_name == _POSTGRESQL_DIALECT:
381+
app_stmt = (
382+
pg_insert(schema.StorageAppState)
383+
.values(app_name=app_name, state={})
384+
.on_conflict_do_nothing(index_elements=["app_name"])
385+
)
386+
user_stmt = (
387+
pg_insert(schema.StorageUserState)
388+
.values(app_name=app_name, user_id=user_id, state={})
389+
.on_conflict_do_nothing(
390+
index_elements=["app_name", "user_id"]
391+
)
392+
)
393+
elif dialect_name == _SQLITE_DIALECT:
394+
app_stmt = (
395+
sqlite_insert(schema.StorageAppState)
396+
.values(app_name=app_name, state={})
397+
.on_conflict_do_nothing()
398+
)
399+
user_stmt = (
400+
sqlite_insert(schema.StorageUserState)
401+
.values(app_name=app_name, user_id=user_id, state={})
402+
.on_conflict_do_nothing()
403+
)
404+
else:
405+
# Fallback for other dialects: use the original get-then-add pattern.
406+
# This is not race-safe but maintains backward compatibility.
407+
storage_app_state = await sql_session.get(
408+
schema.StorageAppState, (app_name)
409+
)
410+
if not storage_app_state:
411+
sql_session.add(
412+
schema.StorageAppState(app_name=app_name, state={})
413+
)
414+
storage_user_state = await sql_session.get(
415+
schema.StorageUserState, (app_name, user_id)
416+
)
417+
if not storage_user_state:
418+
sql_session.add(
419+
schema.StorageUserState(
420+
app_name=app_name, user_id=user_id, state={}
421+
)
422+
)
423+
return
424+
425+
await sql_session.execute(app_stmt)
426+
await sql_session.execute(user_stmt)
427+
362428
@override
363429
async def create_session(
364430
self,
@@ -382,24 +448,24 @@ async def create_session(
382448
raise AlreadyExistsError(
383449
f"Session with id {session_id} already exists."
384450
)
385-
# Fetch app and user states from storage
451+
# Ensure app and user state rows exist using INSERT ... ON CONFLICT
452+
# DO NOTHING to avoid race conditions under concurrent
453+
# create_session calls for the same app_name/user_id.
454+
await self._ensure_state_rows(
455+
sql_session=sql_session,
456+
schema=schema,
457+
app_name=app_name,
458+
user_id=user_id,
459+
)
460+
461+
# Fetch the (now guaranteed to exist) state rows
386462
storage_app_state = await sql_session.get(
387463
schema.StorageAppState, (app_name)
388464
)
389465
storage_user_state = await sql_session.get(
390466
schema.StorageUserState, (app_name, user_id)
391467
)
392468

393-
# Create state tables if not exist
394-
if not storage_app_state:
395-
storage_app_state = schema.StorageAppState(app_name=app_name, state={})
396-
sql_session.add(storage_app_state)
397-
if not storage_user_state:
398-
storage_user_state = schema.StorageUserState(
399-
app_name=app_name, user_id=user_id, state={}
400-
)
401-
sql_session.add(storage_user_state)
402-
403469
# Extract state deltas
404470
state_deltas = _session_util.extract_state_delta(state)
405471
app_state_delta = state_deltas["app"]

‎tests/unittests/sessions/test_session_service.py‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1481,3 +1481,68 @@ async def tracking_fn(**kwargs):
14811481
finally:
14821482
database_session_service._select_required_state = original_fn
14831483
await service.close()
1484+
1485+
1486+
@pytest.mark.asyncio
1487+
async def test_concurrent_create_session_no_unique_violation():
1488+
"""Concurrent create_session calls for the same app_name must not raise.
1489+
1490+
Regression test for https://github.com/google/adk-python/issues/4954.
1491+
Before the fix, the SELECT-then-INSERT pattern on app_states/user_states
1492+
caused UniqueViolation when multiple tasks raced to initialise the same
1493+
app_name on a fresh database.
1494+
"""
1495+
service = DatabaseSessionService('sqlite+aiosqlite:///:memory:')
1496+
try:
1497+
app_name = 'race_test_app'
1498+
num_concurrent = 10
1499+
1500+
# Spawn many concurrent create_session calls for the same app_name
1501+
# but different user_ids — all will try to INSERT the same app_states row.
1502+
sessions = await asyncio.gather(
1503+
*[
1504+
service.create_session(
1505+
app_name=app_name,
1506+
user_id=f'user_{i}',
1507+
)
1508+
for i in range(num_concurrent)
1509+
]
1510+
)
1511+
1512+
# All sessions should have been created successfully (no exceptions)
1513+
assert len(sessions) == num_concurrent
1514+
for i, session in enumerate(sessions):
1515+
assert session.app_name == app_name
1516+
assert session.user_id == f'user_{i}'
1517+
finally:
1518+
await service.close()
1519+
1520+
1521+
@pytest.mark.asyncio
1522+
async def test_concurrent_create_session_same_user_no_unique_violation():
1523+
"""Concurrent create_session for same app_name AND user_id must not raise.
1524+
1525+
This tests the user_states race condition (same composite key).
1526+
"""
1527+
service = DatabaseSessionService('sqlite+aiosqlite:///:memory:')
1528+
try:
1529+
app_name = 'race_test_app'
1530+
user_id = 'shared_user'
1531+
num_concurrent = 10
1532+
1533+
sessions = await asyncio.gather(
1534+
*[
1535+
service.create_session(
1536+
app_name=app_name,
1537+
user_id=user_id,
1538+
)
1539+
for i in range(num_concurrent)
1540+
]
1541+
)
1542+
1543+
assert len(sessions) == num_concurrent
1544+
for session in sessions:
1545+
assert session.app_name == app_name
1546+
assert session.user_id == user_id
1547+
finally:
1548+
await service.close()

0 commit comments

Comments
 (0)