Skip to content

fix(session/database): lock app and user state rows in Create - #1930

Merged
wolo-lab merged 6 commits into
google:mainfrom
Vivek1106-04:fix/database-create-lock-state-rows
Nov 5, 2026
Merged

wolo-lab merged 6 commits into
google:mainfrom
Vivek1106-04:fix/database-create-lock-state-rows

Conversation

@Vivek1106-04

Copy link
Copy Markdown
Contributor

Linked issue

2. Describe the change:

Problem:

Create read the app_states and user_states rows with a plain SELECT, merged the initial state in Go and saved the whole row back. If the row was missing, gorm's Save fell 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's user: keys. A Create running at the same time as an AppendEvent from another session of the same user could drop the append's keys the same way.

Solution:

Create now locks these rows the same way applyEvent does since #1743, using the same lockStateRow helper: insert the row empty if it's missing (ON CONFLICT DO NOTHING), then read it FOR 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 as AppendEvent and the two can't deadlock.

In #1743 I left Create alone because adk-python's create_session doesn'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 helper AppendEvent already uses.

Behavior change

Nothing visible. Create with app: or user: keys in its initial state now takes a row lock on those rows for the length of its transaction.

Testing Plan

Unit Tests:

  • All unit tests pass locally.

TestDatabaseService_Create_LocksSharedStateRows records the statements Create sends to app_states / user_states for 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 tells ON CONFLICT DO NOTHING apart from Save's ON CONFLICT DO UPDATE.

With your source change reverted and your tests kept, which test fails?

--- FAIL: TestDatabaseService_Create_LocksSharedStateRows/app_only
     got ["select app_states" "select user_states" "insert app_states on conflict do update"]
    want ["insert app_states on conflict do nothing" "select app_states for update" "select user_states"]
--- FAIL: TestDatabaseService_Create_LocksSharedStateRows/user_only
--- FAIL: TestDatabaseService_Create_LocksSharedStateRows/app_and_user

With the change, go test -race ./session/... passes and golangci-lint run is clean.

Manual End-to-End (E2E) Tests:

Postgres 18 via fergusstrange/embedded-postgres, 200 runs each:

                                                  main     this PR
2 concurrent Creates, new user, 1 user: key each  50/50 lost   0/200 lost
Create(user:x) vs AppendEvent(user:y), old user    1/50 lost   0/200 lost

All calls returned nil in every run, and no deadlocks. I didn't test MySQL.

Checklist

  • I have read the CONTRIBUTING.md document.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have added tests that prove my fix is effective or that my feature works.
  • New and existing unit tests pass locally with my changes.
  • I have manually tested my changes end-to-end.
  • Any dependent changes have been merged and published in downstream modules.

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
@indurireddy-TF

Copy link
Copy Markdown
Contributor

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.
image

@karolpiotrowicz karolpiotrowicz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Must change before merge:

  • One of the test's failure messages prints &[...] because got is now a pointer (inline).
  • The new helper's doc comment says it records every statement against both tables, but it misses the UPDATE that tx.Save issues (inline).
  • No test covers Create when 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 Create calls for a new user lost one of the user: 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. A Create racing an AppendEvent from 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=1 and 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.

Comment thread session/database/service_test.go Resolved
Comment thread session/database/service_test.go Resolved
Comment thread session/database/service_test.go Resolved
Print the statement list instead of its pointer on failure and narrow the
recorder's doc comment to the inserts and selects it records.
@Vivek1106-04

Copy link
Copy Markdown
Contributor Author

Thanks for running it against Postgres and MySQL. Addressed the three test notes in 715bc60.

@karolpiotrowicz
karolpiotrowicz dismissed their stale review November 1, 2026 14:49

Every item this review raised is fixed and verified on the current head.

@karolpiotrowicz karolpiotrowicz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 Create over existing rows it logs the two inserts and the two selects, and the two UPDATE statements that Save issues go unlogged.
  • TestDatabaseService_Create_KeepsExistingSharedState fails when Create drops 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 into Create. 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.

Comment thread session/database/service_test.go Resolved

@karolpiotrowicz karolpiotrowicz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@wolo-lab
wolo-lab merged commit 2f3b2c2 into google:main Nov 5, 2026
14 checks passed
wolo-lab added a commit that referenced this pull request Nov 16, 2026
, #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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

session/database: Create loses app: and user: state under concurrent writes on Postgres

4 participants