Skip to content

The agent that grows with you

fix(session-search): bound recent-session browsing

Jason Wu98a6e4a90e1d
diff --git a/hermes_state.py b/hermes_state.py
index 1d225138e65..d80326c523c 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -11746,6 +11746,213 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
return {"tokens": int(row[0] or 0), "cost_usd": float(row[1] or 0.0)}
+ def list_recent_sessions_bounded(
+ self,
+ *,
+ limit: int = 20,
+ exclude_sources: List[str] = None,
+ timeout_seconds: float = 3.0,
+ candidate_limit: int = None,
+ lineage_limit: int = None,
+ ) -> List[Dict[str, Any]]:
+ """List recent user conversations without an unbounded message scan.
+
+ This is the latency-bounded browse path used by ``session_search()``.
+ It deliberately separates cheap candidate selection from expensive
+ hydration:
+
+ 1. preselect a small set of session ids from the indexed durable
+ activity timestamp (falling back to ``started_at``);
+ 2. resolve only those candidates across compression ancestry/chains;
+ 3. calculate message-derived activity and previews only for that
+ bounded set.
+
+ Compression ancestry and descendant traversal use ``UNION`` so a
+ corrupt cycle cannot revisit the same session for one logical root,
+ plus a total-row ceiling so a deep or highly branching lineage cannot
+ defeat the candidate bound. If that ceiling is reached before a
+ candidate resolves to a terminal root/tip, that incomplete lineage is
+ omitted from the browse result rather than expanded without bound.
+
+ The query has a cooperative SQLite VM progress deadline. Expensive
+ statements that remain active beyond ``timeout_seconds`` are
+ interrupted at the next progress callback and this method raises
+ ``TimeoutError`` instead of holding a gateway callback indefinitely.
+ Cheap statements may finish between callbacks; the deadline is a
+ fail-safe for sustained work, not a real-time scheduler guarantee.
+
+ This method intentionally supports only the filters needed by the
+ agent-tool browse shape. Rich dashboard/search callers keep using
+ :meth:`list_sessions_rich`.
+ """
+ limit = max(1, int(limit))
+ timeout_seconds = max(0.0, float(timeout_seconds))
+ if candidate_limit is None:
+ candidate_limit = max(128, limit * 8)
+ candidate_limit = max(limit, min(int(candidate_limit), 2048))
+ if lineage_limit is None:
+ lineage_limit = min(8192, candidate_limit * 8)
+ lineage_limit = max(candidate_limit, min(int(lineage_limit), 8192))
+
+ candidate_clauses = [
+ "s.archived = 0",
+ "s.hidden = 0",
+ f"{_delegate_from_json('s.model_config')} IS NULL",
+ ]
+ candidate_params: List[Any] = []
+ if exclude_sources:
+ placeholders = ",".join("?" for _ in exclude_sources)
+ candidate_clauses.append(f"s.source NOT IN ({placeholders})")
+ candidate_params.extend(exclude_sources)
+ candidate_where = " AND ".join(candidate_clauses)
+
+ # A compression continuation is an implementation edge, unlike /new
+ # reset and /branch children which are independent user-visible
+ # conversations. The same predicate is used in both directions so a
+ # candidate tip maps to its logical root and the root maps back to the
+ # freshest live tip.
+ compression_parent_edge = f"""
+ parent.end_reason = 'compression'
+ AND child.parent_session_id = parent.id
+ AND json_extract(
+ COALESCE(child.model_config, '{{}}'), '$._branched_from'
+ ) IS NULL
+ AND {_delegate_from_json('child.model_config')} IS NULL
+ AND COALESCE(child.source, '') != 'tool'
+ """
+
+ query = f"""
+ WITH RECURSIVE
+ recent_candidates(id) AS (
+ SELECT s.id
+ FROM sessions s
+ WHERE {candidate_where}
+ ORDER BY COALESCE(s.last_activity_at, s.started_at) DESC,
+ s.started_at DESC, s.id DESC
+ LIMIT ?
+ ),
+ ancestors(candidate_id, cur_id) AS (
+ SELECT id, id FROM recent_candidates
+ UNION
+ SELECT a.candidate_id, parent.id
+ FROM ancestors a
+ JOIN sessions child ON child.id = a.cur_id
+ JOIN sessions parent ON {compression_parent_edge}
+ LIMIT ?
+ ),
+ candidate_roots(root_id) AS (
+ SELECT DISTINCT a.cur_id
+ FROM ancestors a
+ JOIN sessions child ON child.id = a.cur_id
+ WHERE NOT EXISTS (
+ SELECT 1
+ FROM sessions parent
+ WHERE {compression_parent_edge}
+ )
+ ),
+ chain(root_id, cur_id) AS (
+ SELECT root_id, root_id FROM candidate_roots
+ UNION
+ SELECT c.root_id, child.id
+ FROM chain c
+ JOIN sessions parent ON parent.id = c.cur_id
+ JOIN sessions child ON {compression_parent_edge}
+ LIMIT ?
+ ),
+ chain_rows AS (
+ SELECT
+ c.root_id,
+ c.cur_id,
+ {_sql_session_last_active_by_id('c.cur_id')} AS activity,
+ CASE WHEN EXISTS (
+ SELECT 1
+ FROM sessions parent
+ JOIN sessions child ON {compression_parent_edge}
+ WHERE parent.id = c.cur_id
+ ) THEN 0 ELSE 1 END AS is_tip
+ FROM chain c
+ ),
+ ranked_tips AS (
+ SELECT root_id, cur_id, activity,
+ ROW_NUMBER() OVER (
+ PARTITION BY root_id
+ ORDER BY activity DESC, cur_id DESC
+ ) AS rank_in_root
+ FROM chain_rows
+ WHERE is_tip = 1
+ )
+ SELECT
+ tip.id,
+ tip.source,
+ tip.model,
+ tip.title,
+ s.started_at AS started_at,
+ tip.ended_at,
+ tip.end_reason,
+ tip.message_count,
+ tip.tool_call_count,
+ rt.activity AS last_active,
+ COALESCE(
+ (SELECT {_PREVIEW_RAW_SELECT}
+ FROM messages m
+ WHERE m.session_id = tip.id
+ AND m.role = 'user'
+ AND m.content IS NOT NULL
+ AND {_PREVIEW_ELIGIBLE_SQL}
+ ORDER BY m.timestamp, m.id LIMIT 1),
+ ''
+ ) AS _preview_raw,
+ CASE WHEN s.id != tip.id THEN s.id ELSE NULL END
+ AS _lineage_root_id
+ FROM ranked_tips rt
+ JOIN sessions s ON s.id = rt.root_id
+ JOIN sessions tip ON tip.id = rt.cur_id
+ WHERE rt.rank_in_root = 1
+ AND s.archived = 0
+ AND s.hidden = 0
+ AND {_LISTABLE_CHILD_SQL}
+ AND {_delegate_from_json('s.model_config')} IS NULL
+ ORDER BY rt.activity DESC, s.started_at DESC, tip.id DESC
+ LIMIT ?
+ """
+ params = candidate_params + [
+ candidate_limit,
+ lineage_limit,
+ lineage_limit,
+ limit,
+ ]
+ deadline = time.monotonic() + timeout_seconds
+ interrupted_by_deadline = False
+
+ def _deadline_progress_handler() -> int:
+ nonlocal interrupted_by_deadline
+ if time.monotonic() >= deadline:
+ interrupted_by_deadline = True
+ return 1
+ return 0
+
+ try:
+ with self._read_ctx() as conn:
+ conn.set_progress_handler(_deadline_progress_handler, 1000)
+ try:
+ rows = conn.execute(query, params).fetchall()
+ finally:
+ conn.set_progress_handler(None, 0)
+ except sqlite3.OperationalError as exc:
+ if interrupted_by_deadline and "interrupt" in str(exc).lower():
+ raise TimeoutError(
+ f"recent-session browse exceeded {timeout_seconds:g}s deadline"
+ ) from exc
+ raise
+
+ sessions = []
+ for row in rows:
+ session = self._session_row_dict(row)
+ session["preview"] = _shape_preview(session.pop("_preview_raw", ""))
+ session["unread"] = self.session_unread(session)
+ sessions.append(session)
+ return sessions
+
def list_sessions_rich(
self,
source: str = None,
diff --git a/hermes_state_common.py b/hermes_state_common.py
index af12d322d3b..7de25e6db57 100644
--- a/hermes_state_common.py
+++ b/hermes_state_common.py
@@ -645,6 +645,11 @@ CREATE INDEX IF NOT EXISTS idx_sessions_handoff_state
ON sessions(handoff_state, started_at);
CREATE INDEX IF NOT EXISTS idx_sessions_system_prompt_hash
ON sessions(system_prompt_hash);
+-- Recent-session browsing must never derive recency by scanning messages.
+-- This expression is the durable, indexable approximation used to preselect
+-- a small candidate set before compression-chain and preview hydration.
+CREATE INDEX IF NOT EXISTS idx_sessions_effective_activity
+ ON sessions(COALESCE(last_activity_at, started_at) DESC, started_at DESC);
"""
diff --git a/tests/hermes_state/test_bounded_recent_sessions.py b/tests/hermes_state/test_bounded_recent_sessions.py
new file mode 100644
index 00000000000..6211ff7de06
--- /dev/null
+++ b/tests/hermes_state/test_bounded_recent_sessions.py
@@ -0,0 +1,240 @@
+"""Regression coverage for latency-bounded recent-session browsing."""
+
+import sqlite3
+import time
+
+import pytest
+
+from hermes_state import SessionDB
+
+
+def db(tmp_path):
+ return SessionDB(tmp_path / "state.db")
+
+
+def _set_activity(db, session_id, when):
+ db._conn.execute(
+ "UPDATE sessions SET last_activity_at = ? WHERE id = ?",
+ (when, session_id),
+ )
+ db._conn.commit()
+
+
+def test_bounded_recent_uses_effective_activity_index(db):
+ indexes = {
+ row[0]
+ for row in db._conn.execute(
+ "SELECT name FROM sqlite_master WHERE type = 'index'"
+ ).fetchall()
+ }
+ assert "idx_sessions_effective_activity" in indexes
+
+
+def test_writable_startup_reconciles_legacy_activity_column_before_index(tmp_path):
+ """A pre-last_activity_at store must heal through the real startup path."""
+ path = tmp_path / "legacy-state.db"
+ original = SessionDB(path)
+ original.close()
+
+ conn = sqlite3.connect(path)
+ try:
+ conn.execute("DROP INDEX IF EXISTS idx_sessions_effective_activity")
+ conn.execute("ALTER TABLE sessions DROP COLUMN last_activity_at")
+ conn.commit()
+ finally:
+ conn.close()
+
+ healed = SessionDB(path)
+ try:
+ columns = {
+ row[1] for row in healed._conn.execute("PRAGMA table_info(sessions)")
+ }
+ indexes = {
+ row[0]
+ for row in healed._conn.execute(
+ "SELECT name FROM sqlite_master WHERE type = 'index'"
+ )
+ }
+ assert "last_activity_at" in columns
+ assert "idx_sessions_effective_activity" in indexes
+ assert healed.list_recent_sessions_bounded(limit=1) == []
+ finally:
+ healed.close()
+
+
+def test_bounded_recent_orders_by_durable_activity_and_shapes_preview(db):
+ now = time.time()
+ db.create_session("older", source="cli")
+ db.append_message("older", role="user", content="older preview")
+ db.create_session("newer", source="cli")
+ db.append_message("newer", role="user", content="newer preview")
+ _set_activity(db, "older", now - 20)
+ _set_activity(db, "newer", now - 10)
+
+ rows = db.list_recent_sessions_bounded(limit=2)
+
+ assert [row["id"] for row in rows] == ["newer", "older"]
+ assert rows[0]["preview"] == "newer preview"
+
+
+def test_bounded_recent_maps_recent_compression_tip_to_logical_root(db):
+ now = time.time()
+ db.create_session("root", source="cli")
+ db.append_message("root", role="user", content="root preview")
+ db.end_session("root", "compression")
+ db.create_session("tip", source="cli", parent_session_id="root")
+ db.append_message("tip", role="user", content="tip preview")
+ _set_activity(db, "root", now - 1000)
+ _set_activity(db, "tip", now)
+
+ rows = db.list_recent_sessions_bounded(limit=1)
+
+ assert rows[0]["id"] == "tip"
+ assert rows[0]["_lineage_root_id"] == "root"
+ assert rows[0]["preview"] == "tip preview"
+
+
+def test_bounded_recent_keeps_reset_child_user_visible(db):
+ now = time.time()
+ db.create_session("before-reset", source="cli", session_key="cli:one")
+ db.end_session("before-reset", "session_reset")
+ db.create_session(
+ "after-reset",
+ source="cli",
+ parent_session_id="before-reset",
+ session_key="cli:one",
+ )
+ db.append_message("after-reset", role="user", content="fresh conversation")
+ _set_activity(db, "after-reset", now)
+
+ rows = db.list_recent_sessions_bounded(limit=5)
+
+ assert "after-reset" in [row["id"] for row in rows]
+
+
+def test_bounded_recent_keeps_branch_separate_from_compression_parent(db):
+ now = time.time()
+ db.create_session("branch-parent", source="cli")
+ db.end_session("branch-parent", "compression")
+ db.create_session(
+ "branch-child",
+ source="cli",
+ parent_session_id="branch-parent",
+ model_config={"_branched_from": "branch-parent"},
+ )
+ db.append_message("branch-child", role="user", content="branch preview")
+ _set_activity(db, "branch-child", now)
+
+ rows = db.list_recent_sessions_bounded(limit=5)
+
+ branch = next(row for row in rows if row["id"] == "branch-child")
+ assert branch.get("_lineage_root_id") is None
+
+
+def test_bounded_recent_excludes_delegated_children_and_sources(db):
+ now = time.time()
+ db.create_session("visible", source="cli")
+ db.append_message("visible", role="user", content="visible")
+ _set_activity(db, "visible", now - 1)
+ db.create_session(
+ "delegated",
+ source="cli",
+ model_config={"_delegate_from": "parent"},
+ )
+ db.append_message("delegated", role="user", content="hidden delegate")
+ _set_activity(db, "delegated", now)
+ db.create_session("hidden-source", source="cron")
+ db.append_message("hidden-source", role="user", content="hidden source")
+ _set_activity(db, "hidden-source", now + 1)
+
+ rows = db.list_recent_sessions_bounded(
+ limit=5,
+ exclude_sources=["cron"],
+ )
+
+ assert [row["id"] for row in rows] == ["visible"]
+
+
+def test_bounded_recent_omits_deep_lineage_when_traversal_cap_is_reached(db):
+ now = time.time()
+ parent = None
+ for i in range(40):
+ sid = f"deep-{i}"
+ db.create_session(sid, source="cli", parent_session_id=parent)
+ if parent is not None:
+ db.end_session(parent, "compression")
+ _set_activity(db, sid, now + i)
+ parent = sid
+ db.create_session("visible-deep-peer", source="cli")
+ _set_activity(db, "visible-deep-peer", now + 100)
+
+ rows = db.list_recent_sessions_bounded(
+ limit=5,
+ candidate_limit=8,
+ lineage_limit=8,
+ )
+
+ assert [row["id"] for row in rows] == ["visible-deep-peer"]
+
+
+def test_bounded_recent_omits_branching_lineage_at_total_row_cap(db):
+ now = time.time()
+ db.create_session("fanout-root", source="cli")
+ db.end_session("fanout-root", "compression")
+ for i in range(40):
+ sid = f"fanout-{i}"
+ db.create_session(sid, source="cli", parent_session_id="fanout-root")
+ _set_activity(db, sid, now + i)
+ db.create_session("visible-fanout-peer", source="cli")
+ _set_activity(db, "visible-fanout-peer", now + 100)
+
+ rows = db.list_recent_sessions_bounded(
+ limit=5,
+ candidate_limit=8,
+ lineage_limit=8,
+ )
+
+ assert [row["id"] for row in rows] == ["visible-fanout-peer"]
+
+
+def test_bounded_recent_cycle_is_deduplicated_and_omitted(db):
+ now = time.time()
+ db.create_session("cycle-a", source="cli")
+ db.create_session("cycle-b", source="cli", parent_session_id="cycle-a")
+ db.end_session("cycle-a", "compression")
+ db.end_session("cycle-b", "compression")
+ db._conn.execute(
+ "UPDATE sessions SET parent_session_id = ? WHERE id = ?",
+ ("cycle-b", "cycle-a"),
+ )
+ _set_activity(db, "cycle-a", now)
+ _set_activity(db, "cycle-b", now + 1)
+ db.create_session("visible-cycle-peer", source="cli")
+ _set_activity(db, "visible-cycle-peer", now + 2)
+
+ rows = db.list_recent_sessions_bounded(
+ limit=5,
+ candidate_limit=8,
+ lineage_limit=8,
+ )
+
+ assert [row["id"] for row in rows] == ["visible-cycle-peer"]
+
+
+def test_bounded_recent_deadline_interrupts_sqlite(db):
+ for i in range(300):
+ sid = f"session-{i}"
+ db.create_session(sid, source="cli")
+ db.append_message(sid, role="user", content=f"message {i}")
+
+ with pytest.raises(TimeoutError, match="recent-session browse exceeded"):
+ db.list_recent_sessions_bounded(
+ limit=20,
+ candidate_limit=300,
+ timeout_seconds=0.0,
+ )
+
+ # The progress handler is removed in finally: the same connection remains
+ # usable after cancellation instead of poisoning subsequent gateway reads.
+ assert db.get_session("session-0")["id"] == "session-0"
\ No newline at end of file
diff --git a/tests/test_schema_read_probe.py b/tests/test_schema_read_probe.py
index 9770a8f050a..a1c0c83978c 100644
--- a/tests/test_schema_read_probe.py
+++ b/tests/test_schema_read_probe.py
@@ -62,6 +62,9 @@ class TestSchemaReadProbeStatements:
"""
conn = _fresh_schema_conn()
try:
+ # Indexes that depend on the column must be removed before SQLite
+ # can emulate a pre-column legacy store via DROP COLUMN.
+ conn.execute("DROP INDEX IF EXISTS idx_sessions_effective_activity")
conn.execute("ALTER TABLE sessions DROP COLUMN last_activity_at")
# The failure must come from the sessions probe naming the exact
# column — not incidentally from some other statement — so a
diff --git a/tests/tools/test_session_search.py b/tests/tools/test_session_search.py
index 635bcb91e44..1d428364f2e 100644
--- a/tests/tools/test_session_search.py
+++ b/tests/tools/test_session_search.py
@@ -114,11 +114,41 @@ class TestFormatTimestamp:
# =========================================================================
class TestBrowseShape:
+ def test_browse_uses_bounded_recent_path(self):
+ class _DB:
+ rich_called = False
+ bounded_kwargs = None
+
+ def list_recent_sessions_bounded(self, **kwargs):
+ self.bounded_kwargs = kwargs
+ return []
+
+ def list_sessions_rich(self, **_kwargs):
+ self.rich_called = True
+ raise AssertionError("unbounded rich listing must not be used")
+
+ db = _DB()
+ result = json.loads(session_search(db=db))
+
+ assert result["success"] is True
+ assert db.rich_called is False
+ assert db.bounded_kwargs["timeout_seconds"] == 3.0
+
+ def test_browse_fails_closed_without_bounded_database_capability(self):
+ class _LegacyDB:
+ def list_sessions_rich(self, **_kwargs):
+ raise AssertionError("known-unbounded fallback must not be called")
+
+ result = json.loads(session_search(db=_LegacyDB()))
+
+ assert result["success"] is False
+ assert "does not support bounded recent-session browse" in result["error"]
+
def test_lazy_database_is_released_after_search(self, monkeypatch):
class _DB:
released = 0
- def list_sessions_rich(self, **_kwargs):
+ def list_recent_sessions_bounded(self, **_kwargs):
return []
db = _DB()
@@ -140,7 +170,7 @@ class TestBrowseShape:
def __init__(self):
self.closed = 0
- def list_sessions_rich(self, **_kwargs):
+ def list_recent_sessions_bounded(self, **_kwargs):
return []
def close(self):
diff --git a/tools/session_search_tool.py b/tools/session_search_tool.py
index f2daafeaf12..6ac28a10f01 100644
--- a/tools/session_search_tool.py
+++ b/tools/session_search_tool.py
@@ -485,18 +485,24 @@ def _read_session(db, session_id: str, head: int = 20, tail: int = 10, link_prof
def _list_recent_sessions(db, limit: int, current_session_id: str = None, link_profile: str = None) -> str:
"""Return metadata for the most recent sessions (no LLM calls, no FTS5)."""
try:
- # list_sessions_rich (include_children=False) already applies the
- # canonical child classifier (_LISTABLE_CHILD_SQL): roots, /branch
- # children, and /new-reset children are admitted (stable markers plus
- # the legacy same-key heuristic), while delegation/compression
- # children are hidden. Re-classifying rows here in Python duplicated
- # that predicate and re-hid legacy pre-marker reset children the SQL
- # deliberately admits — trust the query instead (#85756).
- sessions = db.list_sessions_rich(
+ # Never use list_sessions_rich(order_by_last_active=True) here. That
+ # generic query walks every compression chain and derives activity and
+ # previews from messages before LIMIT; on a multi-GB state.db it can
+ # monopolise a gateway callback for minutes. The dedicated browse
+ # query preselects an indexed, bounded candidate set and carries a
+ # cooperative SQLite VM cancellation deadline.
+ bounded_list = getattr(db, "list_recent_sessions_bounded", None)
+ if bounded_list is None:
+ # Fail closed rather than silently returning to the exact
+ # whole-database query shape this path exists to eliminate.
+ raise RuntimeError(
+ "session database does not support bounded recent-session browse"
+ )
+ sessions = bounded_list(
limit=limit + 15,
exclude_sources=list(_HIDDEN_SESSION_SOURCES),
- order_by_last_active=True,
- ) # fetch extra so we can skip current / compression roots
+ timeout_seconds=3.0,
+ )
current_root, has_compression_hop = (
_resolve_to_parent(db, current_session_id)