Skip to content

The agent that grows with you

fix(sessions): rank list pages on ids before projecting, seed chains only from parents

Sibelius Seraphini0dd2f36ffc9e
diff --git a/hermes_state_sessions.py b/hermes_state_sessions.py
index 4e6a9f54308..4b5683ce216 100644
--- a/hermes_state_sessions.py
+++ b/hermes_state_sessions.py
@@ -1394,12 +1394,28 @@ class SessionSessionsMixin:
# rows; MAX over the chain gives effective_last_active in SQL. Do NOT
# require child.started_at >= parent.ended_at: races insert the
# continuation before ended_at is written.
- outer_where, id_params = self._chain_search_where(
- where_sql, (id_query or "").strip().lower(), (search_query or "").strip().lower(),
- )
+ #
+ # The page is ranked and cut on ids alone (``page``); only its rows then
+ # pay for the projection. Projecting in the ranked query made SQLite
+ # build every admitted row's full result — s.*, the resolved system
+ # prompt, the preview subquery over message content — before LIMIT:
+ # 4-11s per page at 25k rows, for LIMIT 1 as much as LIMIT 200.
+ #
+ # Unless a search needs every row's chain (it matches a row's own id and
+ # title through it), only rows that HAVE a child seed the walk. A
+ # childless row's chain is itself alone, so its MAX is just its own
+ # last_active, which the outer COALESCE reads directly. Seeding every
+ # admitted row made the CTE + GROUP BY materialise the whole table on
+ # every page: ~12s of a 13s list on a 25k-session store where 1 row had
+ # a child, at LIMIT 1 or 200.
+ id_needle = (id_query or "").strip().lower()
+ search_needle = (search_query or "").strip().lower()
+ seed_where = where_sql if (id_needle or search_needle) else _where_sql(where_clauses + [
+ "EXISTS (SELECT 1 FROM sessions _seed_c WHERE _seed_c.parent_session_id = s.id)"])
+ outer_where, id_params = self._chain_search_where(where_sql, id_needle, search_needle)
query = f"""
WITH RECURSIVE chain(root_id, cur_id) AS (
- SELECT s.id, s.id FROM sessions s {where_sql}
+ SELECT s.id, s.id FROM sessions s {seed_where}
UNION ALL
SELECT c.root_id, child.id
FROM chain c
@@ -1417,15 +1433,23 @@ class SessionSessionsMixin:
MAX({_sql_session_last_active_by_id("cur_id")}) AS effective_last_active
FROM chain
GROUP BY root_id
+ ),
+ page AS (
+ SELECT s.id AS page_id,
+ COALESCE(cm.effective_last_active, {_sql_session_last_active("s")},
+ {_sql_in_window("s.started_at")}) AS effective_last_active
+ FROM sessions s
+ LEFT JOIN chain_max cm ON cm.root_id = s.id
+ {outer_where}
+ ORDER BY effective_last_active DESC, s.started_at DESC, s.id DESC
+ LIMIT ? OFFSET ?
)
{select_head}{_sql_session_last_active("s")} AS last_active,
- COALESCE(cm.effective_last_active, {_sql_in_window("s.started_at")}) AS _effective_last_active
- FROM sessions s
- LEFT JOIN chain_max cm ON cm.root_id = s.id
+ page.effective_last_active AS _effective_last_active
+ FROM page
+ JOIN sessions s ON s.id = page.page_id
{prompt_join}
- {outer_where}
ORDER BY _effective_last_active DESC, s.started_at DESC, s.id DESC
- LIMIT ? OFFSET ?
"""
params = params + params + id_params + [limit, offset] # WHERE binds twice (seed + outer)
else:
diff --git a/tests/hermes_state/test_list_sessions_recency.py b/tests/hermes_state/test_list_sessions_recency.py
new file mode 100644
index 00000000000..a80fe2a3b27
--- /dev/null
+++ b/tests/hermes_state/test_list_sessions_recency.py
@@ -0,0 +1,49 @@
+"""Recency order of ``list_sessions_rich(order_by_last_active=True)``.
+
+Only sessions with a child seed the compression-chain walk; every childless row
+is ranked by its own last activity. The two kinds must still sort as one list.
+"""
+
+import time
+
+import pytest
+
+from hermes_state import SessionDB
+
+
+def db(tmp_path):
+ database = SessionDB(tmp_path / "state.db")
+ try:
+ yield database
+ finally:
+ database.close()
+
+
+def _session(db: SessionDB, sid: str, started: float, message_at=None, **kwargs):
+ db.create_session(sid, source="cli", **kwargs)
+ if message_at is not None:
+ db.append_message(session_id=sid, role="user", content=f"hello from {sid}")
+ db._conn.execute("UPDATE messages SET timestamp = ? WHERE session_id = ?", (message_at, sid))
+ db._conn.execute(
+ "UPDATE sessions SET started_at = ?, last_activity_at = NULL, message_count = 1 WHERE id = ?",
+ (started, sid),
+ )
+
+
+def test_chained_and_childless_sessions_share_one_recency_order(db):
+ base = time.time() - 1000
+ # A compression chain whose tip holds the newest message of all.
+ _session(db, "root", base)
+ db._conn.execute(
+ "UPDATE sessions SET ended_at = ?, end_reason = 'compression' WHERE id = 'root'", (base + 10,)
+ )
+ _session(db, "tip", base + 20, message_at=base + 90, parent_session_id="root")
+ # Childless: "fresh" started first but was active later than "stale" started.
+ _session(db, "fresh", base + 5, message_at=base + 60)
+ _session(db, "stale", base + 30)
+ db._conn.commit()
+
+ rows = db.list_sessions_rich(order_by_last_active=True)
+
+ assert [s["id"] for s in rows] == ["tip", "fresh", "stale"]