Skip to content

The agent that grows with you

fix(sessions): the orphan sweep spares the open tip of a pinned chat

John Paul Soliva8d619bf6df1f
diff --git a/hermes_state_maintenance.py b/hermes_state_maintenance.py
index ac2818e3ec6..740cde5c9fb 100644
--- a/hermes_state_maintenance.py
+++ b/hermes_state_maintenance.py
@@ -182,7 +182,8 @@ class SessionMaintenanceMixin:
if not (hb_grace is not None and hb_grace >= 0):
hb_grace = hb_staleness
cutoff = (now := time.time()) - max_idle_seconds
- pin_scope = " AND COALESCE(pinned, 0) = 0" if exclude_pinned else ""
+ pin_scope = (f" AND COALESCE(pinned, 0) = 0 AND sessions.id NOT IN ({_PINNED_TAIL_SQL})"
+ if exclude_pinned else "")
orphan_predicate = f"started_at < ? AND {_sql_session_last_active('sessions')} < ?"
heartbeat_params: Tuple[float, ...] = ()
if respect_gateway_heartbeats:
diff --git a/tests/hermes_state/test_pinned_lineage.py b/tests/hermes_state/test_pinned_lineage.py
index 3127e6887a6..5b1c77cd9fb 100644
--- a/tests/hermes_state/test_pinned_lineage.py
+++ b/tests/hermes_state/test_pinned_lineage.py
@@ -40,3 +40,16 @@ def test_bulk_cleanup_spares_a_chat_pinned_before_it_rotated(tmp_path):
assert db.get_compression_lineage("keep") == ["keep", "keep-2"]
assert not db.get_session("keep")["archived"]
assert db.prune_sessions(older_than_days=90, include_pinned=True) == 2
+
+
+def test_orphan_sweep_spares_the_open_tip_of_a_chat_pinned_before_it_rotated(tmp_path):
+ with closing(SessionDB(tmp_path / "state.db")) as db:
+ _pinned_then_rotated(db)
+ db._conn.execute("UPDATE sessions SET pinned = 0, ended_at = NULL, end_reason = NULL,"
+ " last_activity_at = started_at WHERE id = 'keep-2'")
+ db._conn.commit()
+ sweep = dict(max_idle_seconds=90 * 86400, sources=("cli",), respect_gateway_heartbeats=False)
+
+ assert db.sweep_orphaned_sessions(exclude_pinned=True, **sweep) == []
+ assert db.get_session("keep-2")["ended_at"] is None
+ assert db.sweep_orphaned_sessions(exclude_pinned=False, **sweep) == ["keep-2"]