Skip to content

The agent that grows with you

test(gateway): real-DB restart regression for persisted hygiene cooldown (#74136)

Teknium021d1914789f
diff --git a/tests/gateway/test_session_hygiene.py b/tests/gateway/test_session_hygiene.py
index 0d9695f5824..6c21ae6c368 100644
--- a/tests/gateway/test_session_hygiene.py
+++ b/tests/gateway/test_session_hygiene.py
@@ -428,6 +428,9 @@ async def test_session_hygiene_timeout_continues_to_agent_and_sets_cooldown(monk
release_worker = threading.Event()
cleanup_done = threading.Event()
fake_db = MagicMock()
+ # The DB-backed cooldown check calls this before compressing; a bare
+ # MagicMock return would be truthy and skip compression entirely.
+ fake_db.get_compression_failure_cooldown.return_value = None
class SlowCompressAgent:
last_instance = None
@@ -545,7 +548,12 @@ async def test_session_hygiene_timeout_continues_to_agent_and_sets_cooldown(monk
assert elapsed < 2.0
assert worker_started.is_set()
assert runner._run_agent.await_count == 1
- assert runner._hygiene_compression_failure_cooldowns["sess-timeout"] > time.time()
+ # Cooldown must be persisted to the state DB (survives restart, #74136),
+ # not stashed in an in-memory dict.
+ assert fake_db.record_compression_failure_cooldown.called
+ _cd_args = fake_db.record_compression_failure_cooldown.call_args[0]
+ assert _cd_args[0] == "sess-timeout"
+ assert _cd_args[1] > time.time()
timeout_warnings = [s for s in adapter.sent if "Context compression timed out" in s["content"]]
assert len(timeout_warnings) == 1
fake_db.archive_and_compact.assert_not_called()
@@ -585,6 +593,7 @@ async def test_session_hygiene_forces_in_place_compaction_with_bound_session_db(
"</memory_provider_context>"
)
fake_db = MagicMock()
+ fake_db.get_compression_failure_cooldown.return_value = None
async_session_db = SimpleNamespace(
_db=fake_db,
get_session=AsyncMock(
@@ -896,3 +905,181 @@ def _make_progress_runner(monkeypatch, tmp_path, agent_cls, cfg_text):
return runner, adapter, event
+
+
+# ---------------------------------------------------------------------------
+# Cooldown persistence across gateway restarts (#74136)
+# ---------------------------------------------------------------------------
+
+def _make_cooldown_runner(monkeypatch, tmp_path, agent_cls, session_db, session_id):
+ """Scaffolding for the restart-persistence tests: a fresh GatewayRunner
+ wired to a REAL AsyncSessionDB facade (not a MagicMock) so the hygiene
+ cooldown check/write paths exercise the actual SQLite-backed methods."""
+ from hermes_state import AsyncSessionDB
+
+ fake_dotenv = types.ModuleType("dotenv")
+ fake_dotenv.load_dotenv = lambda *args, **kwargs: None
+ monkeypatch.setitem(sys.modules, "dotenv", fake_dotenv)
+
+ fake_run_agent = types.ModuleType("run_agent")
+ fake_run_agent.AIAgent = agent_cls
+ monkeypatch.setitem(sys.modules, "run_agent", fake_run_agent)
+
+ cfg_path = tmp_path / "config.yaml"
+ cfg_path.write_text(
+ "compression:\n"
+ " enabled: true\n"
+ " hygiene_failure_cooldown_seconds: 300\n",
+ encoding="utf-8",
+ )
+
+ gateway_run = importlib.import_module("gateway.run")
+ GatewayRunner = gateway_run.GatewayRunner
+
+ adapter = HygieneCaptureAdapter()
+ runner = object.__new__(GatewayRunner)
+ runner.config = GatewayConfig(
+ platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="fake-token")}
+ )
+ runner.adapters = {Platform.TELEGRAM: adapter}
+ runner._voice_mode = {}
+ runner.hooks = SimpleNamespace(emit=AsyncMock(), loaded_hooks=False)
+ runner.session_store = MagicMock()
+ runner.session_store.get_or_create_session.return_value = SessionEntry(
+ session_key="agent:main:telegram:dm:12345",
+ session_id=session_id,
+ created_at=datetime.now(),
+ updated_at=datetime.now(),
+ platform=Platform.TELEGRAM,
+ chat_type="dm",
+ )
+ runner.session_store.load_transcript.return_value = _make_history(6, content_size=400)
+ runner.session_store.has_any_sessions.return_value = True
+ runner.session_store.rewrite_transcript = MagicMock()
+ runner.session_store.append_to_transcript = MagicMock()
+ runner._running_agents = {}
+ runner._pending_messages = {}
+ runner._pending_approvals = {}
+ # The real async facade over the real SQLite-backed SessionDB — the
+ # production shape. A SimpleNamespace(_db=MagicMock()) here would let
+ # the assertion pass against methods that don't actually persist.
+ runner._session_db = AsyncSessionDB(session_db)
+ runner._is_user_authorized = lambda _source: True
+ runner._set_session_env = lambda _context: None
+ runner._run_agent = AsyncMock(
+ return_value={
+ "final_response": "ok",
+ "messages": [],
+ "tools": [],
+ "history_offset": 0,
+ "last_prompt_tokens": 0,
+ }
+ )
+
+ monkeypatch.setattr(gateway_run, "_hermes_home", tmp_path)
+ monkeypatch.setattr(gateway_run, "_resolve_runtime_agent_kwargs", lambda: {"api_key": "fake"})
+ monkeypatch.setattr(
+ "agent.model_metadata.get_model_context_length",
+ lambda *_args, **_kwargs: 100,
+ )
+
+ event = MessageEvent(
+ text="hello",
+ source=SessionSource(
+ platform=Platform.TELEGRAM,
+ chat_id="12345",
+ chat_type="dm",
+ user_id="12345",
+ ),
+ message_id="1",
+ )
+ return runner, adapter, event
+
+
+async def test_hygiene_compression_cooldown_survives_gateway_restart(
+ monkeypatch, tmp_path
+):
+ """Regression for #74136: the compression-failure cooldown must be
+ persisted to the state DB, not an in-memory dict on the runner.
+
+ Fail a hygiene compression on runner #1, tear the runner down, build a
+ FRESH runner on the SAME database (simulating a gateway restart), and
+ assert the second runner still honors the cooldown — i.e. it does not
+ re-instantiate a compression agent for the same failing session.
+ """
+ from hermes_state import SessionDB
+
+ session_id = "sess-restart"
+ db = SessionDB(db_path=tmp_path / "state.db")
+ try:
+ db.create_session(session_id, "telegram")
+
+ class AbortingCompressAgent:
+ instances = 0
+
+ def __init__(self, **kwargs):
+ type(self).instances += 1
+ self.session_id = kwargs.get("session_id", session_id)
+ self._session_db = kwargs.get("session_db")
+ self._last_compaction_in_place = False
+ self.context_compressor = SimpleNamespace(
+ bind_session_state=MagicMock(),
+ _last_compress_aborted=True,
+ _last_summary_error="aux model exploded",
+ _last_aux_model_failure_model=None,
+ )
+ self.shutdown_memory_provider = MagicMock()
+ self.close = MagicMock()
+
+ def _compress_context(self, messages, *_args, **_kwargs):
+ # Summary generation failed: compressor aborts and returns
+ # the transcript unchanged.
+ return (messages, None)
+
+ runner1, _adapter1, event1 = _make_cooldown_runner(
+ monkeypatch, tmp_path, AbortingCompressAgent, db, session_id
+ )
+ assert await runner1._handle_message(event1) == "ok"
+ assert AbortingCompressAgent.instances == 1
+
+ # The abort must have persisted a cooldown to the DB.
+ state = db.get_compression_failure_cooldown(session_id)
+ assert state is not None and state["remaining_seconds"] > 0, (
+ "hygiene compression abort did not persist a cooldown to the "
+ f"state DB; got {state!r}"
+ )
+
+ # --- simulate a gateway restart: brand-new runner, same DB ---
+ del runner1
+
+ class ShouldNotRunAgent:
+ instances = 0
+
+ def __init__(self, **kwargs):
+ type(self).instances += 1
+ self.context_compressor = SimpleNamespace(
+ bind_session_state=MagicMock(),
+ _last_compress_aborted=False,
+ _last_aux_model_failure_model=None,
+ )
+ self.shutdown_memory_provider = MagicMock()
+ self.close = MagicMock()
+
+ def _compress_context(self, messages, *_args, **_kwargs):
+ return (messages, None)
+
+ runner2, _adapter2, event2 = _make_cooldown_runner(
+ monkeypatch, tmp_path, ShouldNotRunAgent, db, session_id
+ )
+ assert await runner2._handle_message(event2) == "ok"
+ assert ShouldNotRunAgent.instances == 0, (
+ "REGRESSION (#74136): a fresh GatewayRunner on the same state DB "
+ "re-ran the failing hygiene compression — the failure cooldown "
+ "was lost across the restart (in-memory dict instead of the "
+ "DB-backed record/get methods)."
+ )
+ # The user turn itself still runs; only compression is skipped.
+ assert runner2._run_agent.await_count == 1
+ finally:
+ db.close()