Skip to content

Commit 261ba5d

Browse files
committed
fix: Replace per-call Lock creation with shared lock in SQLiteSession
The lock pattern 'with self._lock if self._is_memory_db else threading.Lock()' creates a new Lock object for each operation when using file-based databases, providing no thread safety for concurrent access. This fix uses the shared self._lock for both memory and file databases, ensuring proper synchronization for concurrent operations. Changes: - get_items() (line 123) - add_items() (line 177) - pop_item() (line 218) - clear_session() (line 255) Testing: - Existing test test_sqlite_session_concurrent_access passes - Manual verification shows proper lock reuse - No breaking changes to API or behavior
1 parent d1abf43 commit 261ba5d

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

src/agents/memory/sqlite_session.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
120120

121121
def _get_items_sync():
122122
conn = self._get_connection()
123-
with self._lock if self._is_memory_db else threading.Lock():
123+
with self._lock:
124124
if limit is None:
125125
# Fetch all items in chronological order
126126
cursor = conn.execute(
@@ -174,7 +174,7 @@ async def add_items(self, items: list[TResponseInputItem]) -> None:
174174
def _add_items_sync():
175175
conn = self._get_connection()
176176

177-
with self._lock if self._is_memory_db else threading.Lock():
177+
with self._lock:
178178
# Ensure session exists
179179
conn.execute(
180180
f"""
@@ -215,7 +215,7 @@ async def pop_item(self) -> TResponseInputItem | None:
215215

216216
def _pop_item_sync():
217217
conn = self._get_connection()
218-
with self._lock if self._is_memory_db else threading.Lock():
218+
with self._lock:
219219
# Use DELETE with RETURNING to atomically delete and return the most recent item
220220
cursor = conn.execute(
221221
f"""
@@ -252,7 +252,7 @@ async def clear_session(self) -> None:
252252

253253
def _clear_session_sync():
254254
conn = self._get_connection()
255-
with self._lock if self._is_memory_db else threading.Lock():
255+
with self._lock:
256256
conn.execute(
257257
f"DELETE FROM {self.messages_table} WHERE session_id = ?",
258258
(self.session_id,),

0 commit comments

Comments
 (0)