The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): persist hygiene failure cooldown rung
fangliquanflq39d2d858fd78
diff --git a/gateway/run.py b/gateway/run.pyindex 443af35d0d4..037997d5a92 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -179,19 +179,32 @@ def _hygiene_cooldown_for_failure(state every time, so from the gateway that streak is structurally always 0and only the flat ``hygiene_failure_cooldown_seconds`` could ever berecorded — a session whose summary model always times out retried on that- same fixed interval forever (#79624). Keeping the streak on- ``PersistentState`` outlives the per-run agent, so failures climb.+ same fixed interval forever (#79624). The streak is mirrored to SQLite by+ rotation-stable ``session_key`` so it outlives both the per-run agent and+ gateway restarts; ``PersistentState`` keeps the hot in-process view."""streak = 1+ state = Nonetry:state = gateway._session_state(session_key).persistent- state.hygiene_failure_streak += 1- streak = state.hygiene_failure_streakexcept Exception as exc:- # The caller uses the return value to record the cooldown, so an- # escaping exception would mean NO cooldown at all (hot retry loop) —- # strictly worse than no escalation. Degrade to the base rung.logger.debug("hygiene failure streak update failed: %s", exc)+ session_db = getattr(gateway, "_session_db", None)+ session_db = getattr(session_db, "_db", session_db)+ increment = getattr(session_db, "increment_hygiene_failure_streak", None)+ if callable(increment):+ try:+ streak = max(1, int(increment(session_key)))+ if state is not None:+ state.hygiene_failure_streak = streak+ except Exception as exc:+ logger.debug("hygiene failure streak persist failed: %s", exc)+ if state is not None:+ state.hygiene_failure_streak += 1+ streak = state.hygiene_failure_streak+ elif state is not None:+ state.hygiene_failure_streak += 1+ streak = state.hygiene_failure_streakmultiplier = _HYGIENE_COOLDOWN_LADDER_MULTIPLIERS[min(streak, len(_HYGIENE_COOLDOWN_LADDER_MULTIPLIERS)) - 1]@@ -210,6 +223,14 @@ def _reset_hygiene_failure_streak(gateway, session_key: str) -> None:state.persistent.hygiene_failure_streak = 0except Exception as exc:logger.debug("hygiene failure streak reset failed: %s", exc)+ session_db = getattr(gateway, "_session_db", None)+ session_db = getattr(session_db, "_db", session_db)+ reset = getattr(session_db, "reset_hygiene_failure_streak", None)+ if callable(reset):+ try:+ reset(session_key)+ except Exception as exc:+ logger.debug("hygiene failure streak persistent reset failed: %s", exc)def hygiene_compaction_recovered(diff --git a/gateway/session_state.py b/gateway/session_state.pyindex 65172a27181..d10f8eb0312 100644--- a/gateway/session_state.py+++ b/gateway/session_state.py@@ -163,9 +163,8 @@ class PersistentState:# escalation back to rung 1 while the DB-backed deadline itself survives# (#74136). Keying on `session_key` rather than `session_id` is what buys# correctness across compaction ROTATION (the sid changes, the chat does- # not), which the persisted `compression_*_streak` columns cannot express- # since they key on sid. Making this durable is tracked on #79624 as a- # schema-level follow-up.+ # not). gateway.run mirrors this value to the DB keyed by session_key so+ # the same semantics also survive gateway restarts.hygiene_failure_streak: int = 0diff --git a/hermes_state.py b/hermes_state.pyindex 9bd1ed63dbc..c28f9cb0644 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -6178,6 +6178,42 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)self._execute_write(_do)+ def increment_hygiene_failure_streak(self, session_key: str) -> int:+ """Atomically increment the session-hygiene failure streak for one chat."""+ if not session_key:+ return 1+ result = []++ def _do(conn):+ conn.execute(+ """INSERT INTO gateway_hygiene_state (session_key, failure_streak)+ VALUES (?, 1)+ ON CONFLICT(session_key) DO UPDATE SET+ failure_streak = gateway_hygiene_state.failure_streak + 1""",+ (session_key,),+ )+ row = conn.execute(+ "SELECT failure_streak FROM gateway_hygiene_state WHERE session_key = ?",+ (session_key,),+ ).fetchone()+ result.append(int(row[0]))++ self._execute_write(_do)+ return result[0]++ def reset_hygiene_failure_streak(self, session_key: str) -> None:+ """Clear the persisted session-hygiene failure streak for one chat."""+ if not session_key:+ return++ def _do(conn):+ conn.execute(+ "DELETE FROM gateway_hygiene_state WHERE session_key = ?",+ (session_key,),+ )++ self._execute_write(_do)+def get_compression_ineffective_count(self, session_id: str) -> int:"""Return the persisted ineffective-compaction strike count.diff --git a/hermes_state_common.py b/hermes_state_common.pyindex 7186c8205db..58b3744859d 100644--- a/hermes_state_common.py+++ b/hermes_state_common.py@@ -378,6 +378,11 @@ CREATE TABLE IF NOT EXISTS gateway_routing (PRIMARY KEY (scope, session_key));+CREATE TABLE IF NOT EXISTS gateway_hygiene_state (+ session_key TEXT PRIMARY KEY,+ failure_streak INTEGER NOT NULL DEFAULT 0+);+CREATE TABLE IF NOT EXISTS compression_locks (session_id TEXT PRIMARY KEY,holder TEXT NOT NULL,diff --git a/tests/gateway/test_hygiene_failure_cooldown_ladder.py b/tests/gateway/test_hygiene_failure_cooldown_ladder.pyindex 54afbb11155..d8811dca3a2 100644--- a/tests/gateway/test_hygiene_failure_cooldown_ladder.py+++ b/tests/gateway/test_hygiene_failure_cooldown_ladder.py@@ -89,6 +89,36 @@ class TestCooldownLadder:assert seen == [BASE * m for m in _HYGIENE_COOLDOWN_LADDER_MULTIPLIERS]assert seen == [300.0, 900.0, 2700.0]+ def test_consecutive_failures_escalate_across_gateway_restart(self, tmp_path):+ from hermes_state import SessionDB++ db = SessionDB(db_path=tmp_path / "state.db")+ try:+ db.create_session("before-rotation", "telegram", session_key=KEY)+ first_runner = _Runner()+ first_runner._session_db = db+ assert _hygiene_cooldown_for_failure(first_runner, KEY, BASE) == BASE++ db.create_session(+ "after-rotation",+ "telegram",+ session_key=KEY,+ parent_session_id="before-rotation",+ )+ restarted_runner = _Runner()+ restarted_runner._session_db = db+ assert _hygiene_cooldown_for_failure(+ restarted_runner, KEY, BASE+ ) == BASE * 3++ other_chat_runner = _Runner()+ other_chat_runner._session_db = db+ assert _hygiene_cooldown_for_failure(+ other_chat_runner, "agent:main:telegram:private:999", BASE+ ) == BASE+ finally:+ db.close()+def test_ladder_saturates_at_the_top_rung(self):"""A permanently un-compactable session must not grow without bound."""runner = _Runner()@@ -116,6 +146,24 @@ class TestCooldownLadder:assert runner._session_state(KEY).persistent.hygiene_failure_streak == 0assert _hygiene_cooldown_for_failure(runner, KEY, BASE) == BASE+ def test_reset_returns_restarted_gateway_to_first_rung(self, tmp_path):+ from hermes_state import SessionDB++ db = SessionDB(db_path=tmp_path / "state.db")+ try:+ runner = _Runner()+ runner._session_db = db+ assert _hygiene_cooldown_for_failure(runner, KEY, BASE) == BASE+ _reset_hygiene_failure_streak(runner, KEY)++ restarted_runner = _Runner()+ restarted_runner._session_db = db+ assert _hygiene_cooldown_for_failure(+ restarted_runner, KEY, BASE+ ) == BASE+ finally:+ db.close()+def test_streaks_are_per_session(self):"""One wedged session must not penalize every other chat."""runner = _Runner()diff --git a/tests/gateway/test_session_hygiene.py b/tests/gateway/test_session_hygiene.pyindex 51b806dbb8a..9a3c8d80b73 100644--- a/tests/gateway/test_session_hygiene.py+++ b/tests/gateway/test_session_hygiene.py@@ -1163,5 +1163,17 @@ async def test_hygiene_compression_cooldown_survives_gateway_restart()# The user turn itself still runs; only compression is skipped.assert runner2._run_agent.await_count == 1++ # Once the first deadline expires, the next failed attempt after a+ # restart must use rung 2 (900s), not start over at 300s (#86650).+ db.clear_compression_failure_cooldown(session_id)+ runner3, _adapter3, event3 = _make_cooldown_runner(+ monkeypatch, tmp_path, AbortingCompressAgent, db, session_id+ )+ assert await runner3._handle_message(event3) == "ok"+ assert AbortingCompressAgent.instances == 2+ escalated = db.get_compression_failure_cooldown(session_id)+ assert escalated is not None+ assert escalated["remaining_seconds"] == pytest.approx(900, abs=5)finally:db.close()