fix: FAISS index/docstore race condition (KeyError crash)#1542
Open
gdeyoung wants to merge 1 commit into
Open
Conversation
…r + atomic saves)
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
KeyError: 56397crash insimilarity_search_with_score_by_vectorwhen accessingindex_to_docstore_id[i]. The FAISS index accumulates more vectors than the mapping dict, causing all memory searches to fail.Root Cause
Race condition in the shared
MyFaissobject (class variableMemory.index). When multiple concurrent agents write to FAISS simultaneously (e.g., interactive agent + scheduler tasks):aadd_documents()→ adds vector to FAISS index (ntotalincrements)aadd_documents()→ adds another vectorindex_to_docstore_idmapping and callssave_local()save_local()writesindex.faisswith BOTH vectors butindex.pklwith only Agent A's mapping entryKeyErrorEvidence
Observed the index grow from 56,398 → 56,427 (29 new vectors) during a 10-minute debugging session, with 1 orphaned mapping per concurrent write. Same desync recurred on consecutive days.
Fix (3 layers, defense in depth)
threading.Lockoninsert_documents/update_documentsKeyErrorin both search methodsos.replace()Changes
threading,tempfileMemory._write_lock: dict[str, threading.Lock]_repair_faiss_desync()— finds unmapped index positions and orphan docstore entries, links theminsert_documents,update_documents— wrapped with locksearch_similarity_threshold,search_similarity_threshold_with_scores— try/except KeyError with auto-repair_save_db_file— atomic write via temp dirTesting