Make MongoChatMemoryRepository.saveAll atomic - #6774
Open
kalayciburak wants to merge 1 commit into
Open
Conversation
Wrap delete-and-insert in a Mongo transaction so a failed insert rolls back the prior delete, matching JdbcChatMemoryRepository. Fixes spring-projects#6770 Signed-off-by: Burak KALAYCI <kalayciburak1996@gmail.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
MongoChatMemoryRepository.saveAll()deletes existing conversation messages and then inserts the replacement list without a transaction. If the insert fails after the delete succeeds, the previous conversation history is lost.JdbcChatMemoryRepositoryalready runs the equivalent delete-and-insert flow inside aTransactionTemplate.Fixes #6770
Solution
saveAllinside aTransactionTemplatebacked byMongoTransactionManager(created from theMongoTemplatedatabase factory by default).PlatformTransactionManagervia the builder for advanced setups.MongoTemplate.insertto fail after delete and asserts the original messages are preserved.Note: MongoDB multi-document transactions require a replica set. Testcontainers
MongoDBContaineralready starts as a single-node replica set.Test plan
./mvnw -pl memory-repositories/spring-ai-model-chat-memory-repository-mongodb test -Dtest=MongoChatMemoryRepositoryITshouldPreserveExistingMessagesWhenInsertFails)I hereby agree to the terms of the Spring AI Contributor License / DCO (Signed-off-by on commit).