Skip to content

The agent that grows with you

perf(state): session-list subqueries stay on idx_messages_session under stale planner stats (#119403)

kshitijk4poora1bb2ceb5b5e
diff --git a/hermes_state_common.py b/hermes_state_common.py
index fe8d93248b0..e62fa6fa7c8 100644
--- a/hermes_state_common.py
+++ b/hermes_state_common.py
@@ -155,8 +155,9 @@ def _shape_preview(raw: Any) -> str:
return text[:_PREVIEW_MAX_CHARS] + "..." if len(text) > _PREVIEW_MAX_CHARS else text
-# Correlated ``_preview_raw`` column for a ``sessions s`` row.
-_PREVIEW_RAW_SUBQUERY_SQL = (f"COALESCE((SELECT {_PREVIEW_RAW_SELECT} FROM messages m"
+# Correlated ``_preview_raw`` column for a ``sessions s`` row. ``INDEXED BY`` walks the session in timestamp
+# order and stops at the first eligible row; the planner otherwise may sort the whole session (#119403).
+_PREVIEW_RAW_SUBQUERY_SQL = (f"COALESCE((SELECT {_PREVIEW_RAW_SELECT} FROM messages m INDEXED BY idx_messages_session"
f" WHERE m.session_id = s.id AND m.role = 'user' AND m.content IS NOT NULL AND {_PREVIEW_ELIGIBLE_SQL}"
f" ORDER BY m.timestamp, m.id LIMIT 1), '') AS _preview_raw")
@@ -256,7 +257,10 @@ def _sql_freshest_of(activity: str, session_id_expr: str, started: str) -> str:
Cells outside the ``coerce_epoch`` window (garbage doubles salvaged from a damaged page, TEXT) are
skipped, fallback included, or one bad row pins the session's recency to ``5e+246`` (#91536); a
session with no trusted cell at all is NULL."""
- msg_max = (f"(SELECT MAX(_act_m.timestamp) FROM messages _act_m WHERE _act_m.session_id = {session_id_expr}"
+ # Pinned to the (session_id, timestamp) index: with planner stats older than idx_messages_session_id,
+ # SQLite picks that non-covering index and reads every message row of every listed session (#119403).
+ msg_max = (f"(SELECT MAX(_act_m.timestamp) FROM messages _act_m INDEXED BY idx_messages_session"
+ f" WHERE _act_m.session_id = {session_id_expr}"
f" AND _act_m.timestamp {_SQL_IN_WINDOW})")
return (f"COALESCE((SELECT MAX(_act_v.v) FROM (SELECT {activity} AS v UNION ALL SELECT {msg_max}) _act_v"
f" WHERE _act_v.v {_SQL_IN_WINDOW}), {_sql_in_window(started)})")
diff --git a/hermes_state_sessions.py b/hermes_state_sessions.py
index ba175bddb4b..4fe23496851 100644
--- a/hermes_state_sessions.py
+++ b/hermes_state_sessions.py
@@ -107,7 +107,7 @@ def _workspace_key_clause(key: str) -> Tuple[str, List[str]]:
# The indentation is part of the list_sessions_rich SQL text.
_PREVIEW_COL_SQL = f"""COALESCE(
(SELECT {_PREVIEW_RAW_SELECT}
- FROM messages m
+ FROM messages m INDEXED BY idx_messages_session
WHERE m.session_id = s.id AND m.role = 'user' AND m.content IS NOT NULL
AND {_PREVIEW_ELIGIBLE_SQL}
ORDER BY m.timestamp, m.id LIMIT 1),
diff --git a/hermes_state_telegram.py b/hermes_state_telegram.py
index 34d57e3924e..09e492d2a6b 100644
--- a/hermes_state_telegram.py
+++ b/hermes_state_telegram.py
@@ -71,7 +71,7 @@ _UNLINKED_SELECT_HEAD = f"""
AS _system_prompt_resolved,
COALESCE(
(SELECT {_PREVIEW_RAW_SELECT}
- FROM messages m
+ FROM messages m INDEXED BY idx_messages_session
WHERE m.session_id = s.id AND m.role = 'user' AND m.content IS NOT NULL
AND {_PREVIEW_ELIGIBLE_SQL}
ORDER BY m.timestamp, m.id LIMIT 1),
diff --git a/tests/hermes_state/test_session_list_index_choice.py b/tests/hermes_state/test_session_list_index_choice.py
new file mode 100644
index 00000000000..b6b511b58d5
--- /dev/null
+++ b/tests/hermes_state/test_session_list_index_choice.py
@@ -0,0 +1,56 @@
+"""Session-list reads stay on the (session_id, timestamp) index whatever the planner stats say (#119403).
+
+A ``sqlite_stat1`` written before ``idx_messages_session_id`` existed has no row for that index, so the
+planner guesses it is selective and routes the per-session last-active and preview subqueries through
+it: every listed session then reads all of its message rows (≈1 GB per list on a 125k-message store).
+"""
+
+import sqlite3
+
+from hermes_state import SessionDB
+
+
+def _stale_stats_db(path):
+ db = SessionDB(db_path=path)
+ for i in range(4):
+ sid = f"s{i}"
+ db.create_session(sid, "cli")
+ db.append_messages_batch(sid, [
+ {"role": "user" if j % 2 == 0 else "assistant", "content": f"{sid} message {j}", "timestamp": 1_000 + j}
+ for j in range(40)
+ ])
+ db.set_session_pinned("s0", True)
+ db.close()
+ raw = sqlite3.connect(path)
+ raw.execute("ANALYZE")
+ raw.execute("DELETE FROM sqlite_stat1 WHERE idx = 'idx_messages_session_id'")
+ raw.commit()
+ raw.close()
+
+
+def test_session_list_never_routes_messages_through_the_id_index(tmp_path, monkeypatch):
+ path = tmp_path / "state.db"
+ _stale_stats_db(path)
+ statements = []
+ real_connect = sqlite3.connect
+
+ def traced_connect(*args, **kwargs):
+ conn = real_connect(*args, **kwargs)
+ conn.set_trace_callback(statements.append)
+ return conn
+
+ monkeypatch.setattr(sqlite3, "connect", traced_connect)
+ db = SessionDB(db_path=path)
+ statements.clear()
+ rows = db.list_sessions_rich(limit=2, order_by_last_active=True, include_pinned=True)
+ db.close()
+ monkeypatch.undo()
+
+ assert {r["id"] for r in rows} >= {"s0"} and all(r["preview"] for r in rows)
+ reads = [s for s in statements if s.lstrip().split(None, 1)[0].upper() in ("SELECT", "WITH")]
+ plan_conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
+ plans = [row[3] for sql in reads for row in plan_conn.execute("EXPLAIN QUERY PLAN " + sql)]
+ plan_conn.close()
+ message_searches = [p for p in plans if "idx_messages_session" in p]
+ assert message_searches, plans
+ assert not [p for p in message_searches if "idx_messages_session_id" in p], message_searches