session/database: serialize AppendEvent per session, matching adk-python
adk-python serializes append_event per session in its database service. adk-go's session/database does not, and that difference is behind a class of concurrency bugs here.
What adk-python does
_with_session_lockkeeps oneasyncio.Lockper(app_name, user_id, session_id). It is reference-counted and dropped when the last waiter leaves (L494-L524).append_eventholds that lock across the stale check, the commit and thelast_update_timeupdate (L918-L1011).- It locks the session row with
FOR UPDATEwhere the dialect supports it (L931). - It applies the event to the in-memory session only after the commit (L1014).
What adk-go does
AppendEvent takes no per-session lock and no row lock, so two appends on one session run concurrently and the database sorts it out. With SQLite, one is aborted with a lock error.
It also appends to the in-memory session before persisting (service.go#L391-L398). That has two effects:
- A failed append still leaves its event in
Events(). - Two overlapping appends can land in memory in a different order from storage.
And because appends aren't serialized, every shared field has to be reasoned about on its own. #1244 does that for updatedAt. With appends serialized, most of that reasoning goes away.
This is reachable today: tail-retention compaction appends its summary to the invocation's session while sub-agents are still producing events (internal/llminternal/compaction_processor.go).
Proposal
Match Python in the database backend:
- a per-session mutex in
databaseService, keyed by(appName, userID, sessionID)and held acrossAppendEvent - the in-memory append moved to after the commit
FOR UPDATEon the session fetch where supported
Keying the lock on the session identity rather than the localSession object also covers two handles to the same session, as Python's does.
Only the database backend needs this. Python's Vertex AI, in-memory and SQLite session services take no such lock.
Related
- #1244: the narrow fix for the
updatedAtdata race. It stays scoped to that race. - #1256: refreshing stale handles, which touches the same
AppendEventcode.
Source: google/adk-go