The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(sessions): stop lease refresher at turn boundary
fangliquanflq967391cd4b5c
diff --git a/run_agent.py b/run_agent.pyindex f62ea6a360d..9399fadecf8 100644--- a/run_agent.py+++ b/run_agent.py@@ -8086,11 +8086,21 @@ class AIAgent:durable_turn_lease = Nonedurable_turn_lease_stop = Nonedurable_turn_lease_thread = None+ durable_turn_lease_activity_lock = threading.Lock()+ durable_turn_lease_turn_active = Falsetoken = Noneacct_token = Nonetask_started = Falsetask_finished = Falserelay_outcome = "failed"++ def _stop_durable_turn_lease_refresher() -> None:+ nonlocal durable_turn_lease_turn_active+ with durable_turn_lease_activity_lock:+ durable_turn_lease_turn_active = False+ if durable_turn_lease_stop is not None:+ durable_turn_lease_stop.set()+try:# Serialize the full load -> run -> flush region across Hermes# processes. Gateway's asyncio lease closes alias routing inside one@@ -8260,10 +8270,16 @@ class AIAgent:def _refresh_durable_turn_lease() -> None:def _interrupt_turn(message: str) -> None:- try:- self.interrupt(message, hard_cancel=True)- except Exception:- self._interrupt_requested = True+ with durable_turn_lease_activity_lock:+ if (+ durable_turn_lease_stop.is_set()+ or not durable_turn_lease_turn_active+ ):+ return+ try:+ self.interrupt(message, hard_cancel=True)+ except Exception:+ self._interrupt_requested = Truewhile not durable_turn_lease_stop.wait(_lease_refresh_interval):try:@@ -8300,6 +8316,8 @@ class AIAgent:)return+ with durable_turn_lease_activity_lock:+ durable_turn_lease_turn_active = Truedurable_turn_lease_thread = threading.Thread(target=_refresh_durable_turn_lease,name="session-turn-lease-refresh",@@ -8348,19 +8366,25 @@ class AIAgent:# Keep the scope local instead of storing ContextVar tokens on the agent,# which may be observed from another thread.with bind_subagent_parent(self), scoped_runtime_main({}):- result = run_conversation(- self,- user_message,- system_message,- conversation_history,- effective_task_id,- stream_callback,- persist_user_message,- persist_user_timestamp=persist_user_timestamp,- persist_user_display_kind=persist_user_display_kind,- persist_user_display_metadata=persist_user_display_metadata,- moa_config=moa_config,- )+ try:+ result = run_conversation(+ self,+ user_message,+ system_message,+ conversation_history,+ effective_task_id,+ stream_callback,+ persist_user_message,+ persist_user_timestamp=persist_user_timestamp,+ persist_user_display_kind=persist_user_display_kind,+ persist_user_display_metadata=persist_user_display_metadata,+ moa_config=moa_config,+ )+ finally:+ # The lease remains held through relay/task finalization, but+ # those post-loop steps must not receive a late refresh+ # interrupt that poisons the next turn on this cached agent.+ _stop_durable_turn_lease_refresher()terminal = result if isinstance(result, dict) else {}if terminal.get("interrupted") is True:relay_outcome = "cancelled"@@ -8406,8 +8430,7 @@ class AIAgent:relay_lease)finally:- if durable_turn_lease_stop is not None:- durable_turn_lease_stop.set()+ _stop_durable_turn_lease_refresher()if (durable_turn_lease_thread is not Noneand durable_turn_lease_thread.is_alive()diff --git a/tests/run_agent/test_cross_process_turn_lease.py b/tests/run_agent/test_cross_process_turn_lease.pyindex feb37ad84f8..2d68196dd3e 100644--- a/tests/run_agent/test_cross_process_turn_lease.py+++ b/tests/run_agent/test_cross_process_turn_lease.py@@ -7,6 +7,7 @@ import threadingimport timefrom types import SimpleNamespace+from agent import relay_runtimefrom hermes_state import SessionDBfrom run_agent import AIAgent@@ -384,6 +385,56 @@ def test_run_conversation_interrupts_when_lease_refresh_errors(monkeypatch):assert "could not be refreshed" in str(interrupt_calls[0][0]).lower()+def test_refresh_error_after_loop_completion_does_not_poison_next_turn(monkeypatch):+ db = _DB()+ agent = _agent_with_db(db)+ agent._session_turn_lease_refresh_interval = 0.01+ refresh_started = threading.Event()+ release_refresh = threading.Event()+ interrupt_calls = []++ def track_interrupt(message=None, hard_cancel=False):+ interrupt_calls.append((message, hard_cancel))+ agent._interrupt_requested = True++ agent.interrupt = track_interrupt++ def delayed_refresh_error(session_id, holder, **kwargs):+ refresh_started.set()+ release_refresh.wait(timeout=2.0)+ raise OSError("database unavailable")++ db.refresh_session_turn_lease = delayed_refresh_error++ def fake_run(_agent, _message, _system, history, *_args, **_kwargs):+ assert refresh_started.wait(timeout=2.0)+ return {"final_response": "ok", "messages": history, "failed": False}++ original_finish = relay_runtime.SESSION_COORDINATOR.finish_logical_calls++ def finish_after_refresh(turn, *, outcome):+ release_refresh.set()+ time.sleep(0.05)+ return original_finish(turn, outcome=outcome)++ monkeypatch.setattr("agent.conversation_loop.run_conversation", fake_run)+ monkeypatch.setattr(+ relay_runtime.SESSION_COORDINATOR,+ "finish_logical_calls",+ finish_after_refresh,+ )++ result = AIAgent.run_conversation(+ agent,+ "new message",+ conversation_history=[{"role": "user", "content": "seed"}],+ )++ assert result["final_response"] == "ok"+ assert interrupt_calls == []+ assert agent._interrupt_requested is False++def test_late_refresh_miss_after_release_does_not_interrupt(monkeypatch):db = _DB()agent = _agent_with_db(db)