Skip to content

The agent that grows with you

perf: replace COUNT(*) with LIMIT-based existence checks

skywindbe3be0618281
diff --git a/gateway/session.py b/gateway/session.py
index 92e2a5ae099..e8221bf6bcf 100644
--- a/gateway/session.py
+++ b/gateway/session.py
@@ -2279,7 +2279,7 @@ class SessionStore:
"""
if self._db:
try:
- return self._db.session_count() > 1
+ return self._db.session_count_ge(2)
except Exception:
pass # fall through to heuristic
# Fallback: check if sessions.json was loaded with existing data.
diff --git a/hermes_state.py b/hermes_state.py
index f14f1dde773..9397033a60c 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -7333,6 +7333,17 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
cursor = self._conn.execute(f"SELECT COUNT(*) FROM sessions s{where_sql}", params)
return cursor.fetchone()[0]
+ def session_count_ge(self, n: int = 1) -> bool:
+ """Check if at least N sessions exist.
+
+ Short-circuits via LIMIT — much cheaper than COUNT(*) when
+ you only need an existence check. Use this instead of
+ ``session_count() >= n`` when the exact count is irrelevant.
+ """
+ cursor = self._conn.execute("SELECT 1 FROM sessions LIMIT ?", (n,))
+ rows = cursor.fetchall()
+ return len(rows) >= n
+
def session_count_by_source(
self,
*,
@@ -7558,9 +7569,9 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
def _do(conn):
cursor = conn.execute(
- "SELECT COUNT(*) FROM sessions WHERE id = ?", (session_id,)
+ "SELECT 1 FROM sessions WHERE id = ? LIMIT 1", (session_id,)
)
- if cursor.fetchone()[0] == 0:
+ if cursor.fetchone() is None:
return False
if expected_ids is not None:
actual_ids = {
diff --git a/tests/gateway/test_session.py b/tests/gateway/test_session.py
index 5b48ddd22da..9b68bbc352b 100644
--- a/tests/gateway/test_session.py
+++ b/tests/gateway/test_session.py
@@ -1163,15 +1163,39 @@ class TestHasAnySessions:
return s
def test_uses_database_count_when_available(self, store_with_mock_db):
- """has_any_sessions should use database session_count, not len(_entries)."""
+ """has_any_sessions should use database session_count_ge, not len(_entries)."""
store = store_with_mock_db
# Simulate single-platform user with only 1 entry in memory
store._entries = {"telegram:12345": MagicMock()}
# But database has 3 sessions (current + 2 previous resets)
- store._db.session_count.return_value = 3
+ store._db.session_count_ge.return_value = True
assert store.has_any_sessions() is True
- store._db.session_count.assert_called_once()
+ store._db.session_count_ge.assert_called_once_with(2)
+
+ def test_first_session_ever_returns_false(self, store_with_mock_db):
+ """First session ever should return False (only current session in DB)."""
+ store = store_with_mock_db
+ store._entries = {"telegram:12345": MagicMock()}
+ # Database has exactly 1 session (the current one just created)
+ store._db.session_count_ge.return_value = False
+
+ assert store.has_any_sessions() is False
+
+ def test_fallback_without_database(self, tmp_path):
+ """Should fall back to len(_entries) when DB is not available."""
+ config = GatewayConfig()
+ with patch("gateway.session.SessionStore._ensure_loaded"):
+ store = SessionStore(sessions_dir=tmp_path, config=config)
+ store._loaded = True
+ store._db = None
+ store._entries = {"key1": MagicMock(), "key2": MagicMock()}
+
+ # > 1 entries means has sessions
+ assert store.has_any_sessions() is True
+
+ store._entries = {"key1": MagicMock()}
+ assert store.has_any_sessions() is False
class TestLastPromptTokens:
diff --git a/tests/test_hermes_state.py b/tests/test_hermes_state.py
index 715b5e59af2..c16b3607a8a 100644
--- a/tests/test_hermes_state.py
+++ b/tests/test_hermes_state.py
@@ -816,6 +816,22 @@ class TestCounts:
+ def test_session_count_ge_empty(self, db):
+ """session_count_ge should return False for 0 sessions."""
+ assert db.session_count_ge(1) is False
+ assert db.session_count_ge(2) is False
+
+ def test_session_count_ge_at_threshold(self, db):
+ """session_count_ge should True when count >= n."""
+ db.create_session("s1", "cli")
+ assert db.session_count_ge(1) is True
+ assert db.session_count_ge(2) is False
+
+ db.create_session("s2", "telegram")
+ assert db.session_count_ge(1) is True
+ assert db.session_count_ge(2) is True
+ assert db.session_count_ge(3) is False
+
def test_message_count_total(self, db):
assert db.message_count() == 0
db.create_session(session_id="s1", source="cli")