The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): reject negative retention bounds in session prune paths
beardthelion5a56f1097be4
diff --git a/hermes_state_gateway.py b/hermes_state_gateway.pyindex 13af59e250b..aa5a00b3f1f 100644--- a/hermes_state_gateway.py+++ b/hermes_state_gateway.py@@ -315,6 +315,10 @@ class SessionGatewayMixin:That is exactly the shape of a leaked test fixture (#82770) — and also of a chat that was routed butnever answered."""+ if older_than_days < 0:+ raise ValueError(+ f"older_than_days must be >= 0, got {older_than_days!r}: a negative "+ "retention builds a future cutoff that matches every never-active keyed row.")cutoff = time.time() - (float(older_than_days) * 86400.0)rows = self._read_all("""diff --git a/hermes_state_maintenance.py b/hermes_state_maintenance.pyindex 71f038be1a8..bb1815d9e54 100644--- a/hermes_state_maintenance.py+++ b/hermes_state_maintenance.py@@ -203,6 +203,10 @@ class SessionMaintenanceMixin:"""Translate the legacy age window into the shared activity filter, then build WHERE."""if (older_than_days is not None and filters.get("last_active_before") is Noneand filters.get("started_before") is None):+ if older_than_days < 0:+ raise ValueError(+ f"older_than_days must be >= 0, got {older_than_days!r}: a negative "+ "retention builds a future cutoff that matches every ended session.")filters["last_active_before"] = time.time() - (older_than_days * 86400)return self._prune_filter_where(source=source, **filters)@@ -382,6 +386,13 @@ class SessionMaintenanceMixin:"""from hermes_state_repair import _release_auto_maintenance_lock, _try_acquire_auto_maintenance_lockresult: Dict[str, Any] = {"skipped": False, "pruned": 0, "closed": 0, "vacuumed": False}+ if retention_days is None or retention_days < 0:+ # A negative retention would build a future cutoff and match every ended+ # session; auto_prune=false is the disable switch, not a negative bound.+ logger.warning("state.db auto-maintenance skipped: retention_days=%r is invalid",+ retention_days)+ result["skipped"] = True+ return resultmaintenance_lock = _try_acquire_auto_maintenance_lock(self.db_path)if maintenance_lock is None:result["skipped"] = Truediff --git a/tests/hermes_cli/test_session_vacuum_config.py b/tests/hermes_cli/test_session_vacuum_config.pyindex 08f9e175bd3..d38aee5e26d 100644--- a/tests/hermes_cli/test_session_vacuum_config.py+++ b/tests/hermes_cli/test_session_vacuum_config.py@@ -89,6 +89,33 @@ def test_loader_yields_new_defaults_for_fresh_home(monkeypatch, tmp_path: Path):assert sessions.get("retention_days") == 90+def test_negative_retention_days_in_config_deletes_nothing(monkeypatch, tmp_path: Path):+ """E2E through the real startup path: ``sessions.retention_days: -1`` reaches+ ``maybe_auto_prune_and_vacuum`` from this config loader; without validation it+ builds a future cutoff and deletes every ended session."""+ import cli+ import hermes_cli.config+ import hermes_constants+ from hermes_state import SessionDB++ session_db = SessionDB(db_path=tmp_path / "state.db")+ try:+ session_db.create_session(session_id="ended", source="cli")+ session_db.end_session("ended", "done")+ monkeypatch.setattr(+ hermes_cli.config,+ "load_config",+ lambda: {"sessions": {"auto_prune": True, "retention_days": -1}},+ )+ monkeypatch.setattr(hermes_constants, "get_hermes_home", lambda: tmp_path)++ cli._run_state_db_auto_maintenance(session_db)++ assert session_db.get_session("ended") is not None+ finally:+ session_db.close()++def test_cli_auto_maintenance_forwards_vacuum_interval(monkeypatch, tmp_path: Path):import cliimport hermes_cli.configdiff --git a/tests/hermes_state/test_hermes_state.py b/tests/hermes_state/test_hermes_state.pyindex 083b1774df9..3b68e5ab3c9 100644--- a/tests/hermes_state/test_hermes_state.py+++ b/tests/hermes_state/test_hermes_state.py@@ -1382,6 +1382,29 @@ class TestPruneSessions:older_than_days=90, source="cron", archived=False)} == {"ended"}+ def test_negative_older_than_days_rejected(self, db):+ """A negative bound builds a FUTURE cutoff, matching every ended session —+ it must raise instead of mass-deleting (config-fed via sessions.retention_days)."""+ db.create_session(session_id="ended", source="cli")+ db.end_session("ended", "done")+ with pytest.raises(ValueError, match="older_than_days"):+ db.prune_sessions(older_than_days=-1)+ with pytest.raises(ValueError, match="older_than_days"):+ db.list_prune_candidates(older_than_days=-1)+ with pytest.raises(ValueError, match="older_than_days"):+ db.count_prune_matches(older_than_days=-1)+ assert db.get_session("ended") is not None++ def test_negative_never_active_keyed_rejected(self, db):+ """list_never_active_keyed_sessions shares the same future-cutoff hazard."""+ db.create_session(session_id="keyed", source="telegram",+ session_key="telegram:dm:1")+ with pytest.raises(ValueError, match="older_than_days"):+ db.list_never_active_keyed_sessions(older_than_days=-1)+ with pytest.raises(ValueError, match="older_than_days"):+ db.prune_never_active_keyed_sessions(older_than_days=-1)+ assert db.get_session("keyed") is not None+@@ -3903,6 +3926,18 @@ class TestAutoMaintenance:assert second["pruned"] == 0assert db.get_session("old2") is not None # untouched+ def test_negative_retention_days_skips_maintenance(self, db):+ """sessions.retention_days: -1 in config reaches here via cli.py/gateway:+ a future cutoff would match every ended session, so maintenance must+ warn and skip, not delete."""+ self._make_old_ended(db, "old", days_old=100)+ result = db.maybe_auto_prune_and_vacuum(+ retention_days=-1, min_interval_hours=0+ )+ assert result["skipped"] is True+ assert result["pruned"] == 0+ assert db.get_session("old") is not None+