fix: thread-safety in SQLiteSession and AdvancedSQLiteSession with shared lock (Finish)#2831
fix: thread-safety in SQLiteSession and AdvancedSQLiteSession with shared lock (Finish)#2831KirobotDev wants to merge 1 commit intoopenai:mainfrom
Conversation
seratch
left a comment
There was a problem hiding this comment.
Thanks for sharing this. I don't think this patch fully closes the thread-safety gap yet.
AdvancedSQLiteSession.add_items() calls SQLiteSession.add_items() first, and SQLiteSession still uses a fresh threading.Lock() for file-backed DBs. So concurrent writes can still interleave before the advanced-session-specific code takes _file_db_lock.
Could we move the shared file-DB lock to the base SQLiteSession path (or otherwise make both base and advanced code use the same per-instance lock), and add a regression test that exercises concurrent AdvancedSQLiteSession access against a file-backed DB?
|
Thanks for the detailed feedback! You're absolutely right - my fix only addressed the symptom in AdvancedSQLiteSession while leaving the root cause in the base SQLiteSession untouched. Issues identified: This means concurrent calls to base methods like add_items() can still interleave with AdvancedSQLiteSession operations since they use different lock instances. Proposed approach: I'll update the PR to : Should I proceed with this approach, or would you prefer a different solution making the lock injectable or using asyncio.Lock throughout? |
- Add shared _file_db_lock in base SQLiteSession class - Replace fresh threading.Lock() calls with shared instance lock - Ensure AdvancedSQLiteSession inherits the same lock - Add regression tests for concurrent file DB access
|
Thanks again for iterating on this. I took a closer look from the current session implementation and I think there’s a slightly different fix shape that addresses a more important race. The shared per-instance file lock in this PR is an improvement over creating a fresh So I think the stronger fix is:
I have an alternative at #2843. Please feel free to share feedback if you have any. |
Thanks for the detailed feedback! I've updated the PR to address all the concerns:
Changes Made
Shared lock moved to base class (
sqlite_session.py)self._file_db_lock = threading.Lock()inSQLiteSession.__init__()get_items()add_items()pop_item()clear_session()AdvancedSQLiteSession now inherits the lock
_file_db_lockfrom base classself._file_db_lockinstead ofthreading.Lock()Regression tests added
test_concurrent_file_db_access_regression(): Tests 30 concurrent writes from 3 taskstest_concurrent_mixed_operations_file_db(): Tests interleaved add/get operationsBoth tests use file-backed databases (not in-memory) to verify thread safety.
Problem Solved
Previously,
threading.Lock()created fresh lock instances per method call → no actual locking. Now both base and derived classes use the same per-instance lock → proper thread safety for concurrent file DB access.Ready for review!