spring-ai icon indicating copy to clipboard operation
spring-ai copied to clipboard

JdbcChatMemoryRepository.saveAll() deadlocks on MySQL/MariaDB under concurrent saves to different conversations (REPEATABLE_READ gap locks)

Open seeun0210 opened this issue 4 months ago • 0 comments

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_READ isolation
    • 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

  1. Configure JdbcChatMemoryRepository with only a DataSource pointing at MySQL (or MariaDB) — so the repository creates its own DataSourceTransactionManager at the connection's default REPEATABLE_READ.
  2. From several threads, concurrently call saveAll() for distinct, previously unseen conversation ids.
  3. Arrange the transactions so their DELETE statements all execute before any INSERT (e.g. a barrier that pauses each save right after its delete).
  4. Observe the Deadlock found when trying to get lock failure.

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.

seeun0210 avatar Jul 21 '26 06:07 seeun0210