fix(state): add missing thread lock to session_count() and message_count()

Both methods accessed self._conn without self._lock, breaking the
thread-safety contract documented on SessionDB (line 111). All 22 other
DB methods use with self._lock — these two were the only exceptions.

In the gateway's multi-threaded environment (multiple platform reader
threads + single writer) this could cause cursor interleaving,
sqlite3.ProgrammingError, or inconsistent COUNT results.

Closes #2130
This commit is contained in:
Hermes
2026-03-21 10:15:06 +00:00
committed by Teknium
parent f3301a31d5
commit 2de42ba690

View File

@@ -855,23 +855,25 @@ class SessionDB:
def session_count(self, source: str = None) -> int:
"""Count sessions, optionally filtered by source."""
if source:
cursor = self._conn.execute(
"SELECT COUNT(*) FROM sessions WHERE source = ?", (source,)
)
else:
cursor = self._conn.execute("SELECT COUNT(*) FROM sessions")
return cursor.fetchone()[0]
with self._lock:
if source:
cursor = self._conn.execute(
"SELECT COUNT(*) FROM sessions WHERE source = ?", (source,)
)
else:
cursor = self._conn.execute("SELECT COUNT(*) FROM sessions")
return cursor.fetchone()[0]
def message_count(self, session_id: str = None) -> int:
"""Count messages, optionally for a specific session."""
if session_id:
cursor = self._conn.execute(
"SELECT COUNT(*) FROM messages WHERE session_id = ?", (session_id,)
)
else:
cursor = self._conn.execute("SELECT COUNT(*) FROM messages")
return cursor.fetchone()[0]
with self._lock:
if session_id:
cursor = self._conn.execute(
"SELECT COUNT(*) FROM messages WHERE session_id = ?", (session_id,)
)
else:
cursor = self._conn.execute("SELECT COUNT(*) FROM messages")
return cursor.fetchone()[0]
# =========================================================================
# Export and cleanup