JdbcChatMemoryRepository.saveAll() deadlocks on MySQL/MariaDB under concurrent saves to different conversations (REPEATABLE_READ gap locks)
Bug description
JdbcChatMemoryRepository.saveAll() replaces a conversation's history by deleting the existing rows for the conversation id and then inserting the replacement messages, all within a single transaction.
On MySQL and MariaDB — whose default transaction isolation is REPEATABLE_READ — the DELETE for a not-yet-existing conversation id acquires gap locks on the index range. When multiple threads concurrently saveAll() for different, previously unseen conversation ids, these gap locks can overlap, and the subsequent inserts deadlock:
Deadlock found when trying to get lock; try restarting transaction
The deletes and inserts are individually correct; the problem is the gap-locking behavior of the missing-row deletes under REPEATABLE_READ, which is specific to MySQL/MariaDB. PostgreSQL, H2, and SQL Server do not exhibit it.
Environment
- Spring AI version: 2.0.0 (confirmed still present on
main) - Module:
spring-ai-model-chat-memory-repository-jdbc - Database: MySQL / MariaDB, default
REPEATABLE_READisolation- Reproduced on MySQL 8.x and MariaDB 10.3.39
- Not reproducible on PostgreSQL 17, H2, or SQL Server 2022
- Java 21
Steps to reproduce
- Configure
JdbcChatMemoryRepositorywith only aDataSourcepointing at MySQL (or MariaDB) — so the repository creates its ownDataSourceTransactionManagerat the connection's defaultREPEATABLE_READ. - From several threads, concurrently call
saveAll()for distinct, previously unseen conversation ids. - Arrange the transactions so their
DELETEstatements all execute before anyINSERT(e.g. a barrier that pauses each save right after its delete). - Observe the
Deadlock found when trying to get lockfailure.
Expected behavior
Concurrent saveAll() calls for different conversation ids should not contend with each other — each should commit independently without deadlocking, on MySQL/MariaDB just as on the other supported databases.
Minimal Complete Reproducible example
A deterministic MySQL integration test that reproduces this via a four-save barrier (pausing each concurrent save after its delete) is included in the proposed fix, PR #6649 — JdbcChatMemoryRepositoryMysqlIT. It fails on main with Deadlock found when trying to get lock and passes with the fix.