Repository navigation
fix(session/database): lock app and user state rows in Create - #1930
Conversation
Create read the app and user state rows without a lock and wrote them back whole through Save's upsert. On Postgres or MySQL, two sessions created at once for a new user both read no row and the later upsert replaced the earlier one's user: keys. A Create racing an AppendEvent from another session could also drop the append's keys. Lock the rows the same way AppendEvent does since google#1743: insert the row if it is missing and read it FOR UPDATE, app before user, only for the scopes the initial state changes. Fixes google#1929
|
Hi @Vivek1106-04 Thanks for the fix! The changes look good. I verified them locally: applying lockStateRow with app before user ordering cleanly resolves the concurrent write issue in Create without deadlocks, and TestDatabaseService_Create_LocksSharedStateRows passes without issues. |
karolpiotrowicz
left a comment
There was a problem hiding this comment.
Must change before merge:
- One of the test's failure messages prints
&[...]becausegotis now a pointer (inline). - The new helper's doc comment says it records every statement against both tables, but it misses the
UPDATEthattx.Saveissues (inline). - No test covers
Createwhen the app and user state rows already exist, which is the branch the new locking exists for (inline).
The fix itself holds up:
I checked this against real PostgreSQL 16 and MySQL 8.4 databases. Two calls were started together through the public Create / AppendEvent API, 100 runs per scenario, and afterwards every key was checked with Get.
- Without the change, two
Createcalls for a new user lost one of theuser:keys in 99 of 100 runs on Postgres. On MySQL the same pair deadlocked (Error 1213) in 82 to 90 of 100 runs, and every other run lost a key. ACreateracing anAppendEventfrom another session lost keys in 3 to 100 of 100 runs, depending on which scopes the two calls touched. - With the change, every scenario came back with 0 lost keys, 0 errors and 0 deadlocks on both databases, at
GOMAXPROCS=1and 64. A further run confirmed that keys already in the rows before the race survive too.
The lock order matches applyEvent, and the new test fails with the service.go change reverted.
Separate from this change, the same MySQL runs hit #1928. The first AppendEvent on a session returned by Create fails with "stale session error" in 47 of 100 serial runs, because Create returns an updatedAt that was never truncated to microseconds (storage_session.go#L50, service.go#L174). It behaves the same on main, and #1950 is working on it.
Three small test notes are inline.
Print the statement list instead of its pointer on failure and narrow the recorder's doc comment to the inserts and selects it records.
|
Thanks for running it against Postgres and MySQL. Addressed the three test notes in 715bc60. |
Every item this review raised is fixed and verified on the current head.
karolpiotrowicz
left a comment
There was a problem hiding this comment.
The three points from my earlier review are addressed. I checked each one against this head:
- The AppendEvent test's failure message now prints the statement list instead of its pointer.
- The helper's comment now matches what it records. On a second
Createover existing rows it logs the two inserts and the two selects, and the twoUPDATEstatements thatSaveissues go unlogged. TestDatabaseService_Create_KeepsExistingSharedStatefails whenCreatedrops the keys already stored in the app row or in the user row, or overwrites a row instead of merging into it. I injected each of those three faults intoCreate. All three passed the previous version of the tests, and each now fails this test and only this test.
I re-ran the same checks as before on this head merged with current main, and they were all clean.
One optional note on the new test is inline.
karolpiotrowicz
left a comment
There was a problem hiding this comment.
The distinct user keys work. Filling the user row from the app row's merged state before the save now fails TestDatabaseService_Create_KeepsExistingSharedState, and so does the mirror case, where the app row starts from the user row's stored keys. Both passed the previous version of the test and the rest of the package, and each now fails this test and only this test. Skipping the save of an existing app row or user row fails it too.
I re-ran the same checks as before on this head, and the results match my earlier review.
, #1919, #2189, #2285) (#2346) * fix(session/vertexai): drop temp: keys from the initial state on Create (#2100) (cherry picked from commit 0c109f7) * fix(session): keep in-memory Get from returning events before After (#2089) (cherry picked from commit 10395f0) * fix(session/database): lock app and user state rows in Create (#1930) (cherry picked from commit 2f3b2c2) * fix(session/database): delete a session's events explicitly in Delete (#1774) (cherry picked from commit 7af0f5f) * fix(session): define List order as last update time ascending (#1919) (cherry picked from commit 8be7e25) * fix(session): skip nil parts in IsFinalResponse classification (#2189) (cherry picked from commit 75ae920) * fix(session): count a final error event as a final response (#2285) (cherry picked from commit d9ecb34)

Linked issue
2. Describe the change:
Problem:
Createread theapp_statesanduser_statesrows with a plainSELECT, merged the initial state in Go and saved the whole row back. If the row was missing, gorm'sSavefell back to an upsert. On Postgres, two sessions created at once for a new user both read no row, and the later upsert replaced the earlier one'suser:keys. ACreaterunning at the same time as anAppendEventfrom another session of the same user could drop the append's keys the same way.Solution:
Createnow locks these rows the same wayapplyEventdoes since #1743, using the samelockStateRowhelper: insert the row empty if it's missing (ON CONFLICT DO NOTHING), then read itFOR UPDATE. It only does this for the scopes the initial state actually has keys for, and always app before user, so it takes locks in the same order asAppendEventand the two can't deadlock.In #1743 I left
Createalone because adk-python'screate_sessiondoesn't lock these rows. It does get-or-create them with a savepoint though (_get_or_create_state), which covers the new-user case. This goes a bit further and also covers the existing-user case, since it's the same helperAppendEventalready uses.Behavior change
Nothing visible.
Createwithapp:oruser:keys in its initial state now takes a row lock on those rows for the length of its transaction.Testing Plan
Unit Tests:
TestDatabaseService_Create_LocksSharedStateRowsrecords the statementsCreatesends toapp_states/user_statesfor each state scope, the same way the AppendEvent test does. CI runs on SQLite, which serializes writers, so it checks that the lock is taken rather than reproducing the race. I moved the statement recorder out of the AppendEvent test into a shared helper, and it now tellsON CONFLICT DO NOTHINGapart fromSave'sON CONFLICT DO UPDATE.With your source change reverted and your tests kept, which test fails?
With the change,
go test -race ./session/...passes andgolangci-lint runis clean.Manual End-to-End (E2E) Tests:
Postgres 18 via
fergusstrange/embedded-postgres, 200 runs each:All calls returned nil in every run, and no deadlocks. I didn't test MySQL.
Checklist