The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(relay): close concurrent logical scopes in stack order
Alex Fournier1a60a496801a
diff --git a/agent/relay_llm.py b/agent/relay_llm.pyindex 71586844b1b..06fbeaf4449 100644--- a/agent/relay_llm.py+++ b/agent/relay_llm.py@@ -695,24 +695,13 @@ def _complete_logical(output.update({"model": model_name, "provider": provider_name})if response_model_name is not None:output["response_model"] = response_model_name- with turn.finalize_lock:- with turn.logical_llm_lock:- if turn.logical_llm_calls.get(request_id) is not handle:- return- if lease.session is None:- return- try:- (operation_lease or lease.host).run_in_session(- lease.session, relay_runtime.pop_relay_scope, lease.host.relay, handle,- output=output, metadata=relay_runtime.runtime_metadata(lease.host.runtime_id),- )- except Exception:- # Provider result is authoritative; retain the handle so turn finalization can retry.- logger.warning("Hermes Relay logical LLM finalization failed", exc_info=True)- return- with turn.logical_llm_lock:- if turn.logical_llm_calls.get(request_id) is handle:- del turn.logical_llm_calls[request_id]+ relay_runtime.SESSION_COORDINATOR.complete_logical_call(+ turn,+ request_id=request_id,+ handle=handle,+ output=output,+ operation_lease=operation_lease,+ )def _is_cancellation(error: BaseException) -> bool:diff --git a/agent/relay_runtime.py b/agent/relay_runtime.pyindex 580ecb8f647..df2f3252c23 100644--- a/agent/relay_runtime.py+++ b/agent/relay_runtime.py@@ -815,6 +815,7 @@ class RelayTurnContext:task_id: strhandle: Any = Nonelogical_llm_calls: dict[str, Any] = field(default_factory=dict, repr=False)+ logical_llm_outputs: dict[str, dict[str, Any]] = field(default_factory=dict, repr=False)logical_llm_lock: threading.RLock = field(default_factory=threading.RLock, repr=False)finalize_lock: threading.RLock = field(default_factory=threading.RLock, repr=False)_previous_turn: RelayTurnContext | None = field(default=None, repr=False)@@ -1070,30 +1071,86 @@ class RelaySessionCoordinator:if not turn.closed:self._finish_logical_calls(turn, outcome=outcome)+ def complete_logical_call(+ self,+ turn: RelayTurnContext,+ *,+ request_id: str,+ handle: Any,+ output: dict[str, Any],+ operation_lease: RelayOperationLease | None = None,+ ) -> None:+ """Close completed logical calls once they reach the Relay stack top."""+ with turn.finalize_lock:+ with turn.logical_llm_lock:+ if turn.logical_llm_calls.get(request_id) is not handle:+ return+ turn.logical_llm_outputs[request_id] = dict(output)+ self._drain_completed_logical_calls(+ turn,+ operation_lease=operation_lease,+ )++ def _finish_logical_calls(self, turn: RelayTurnContext, *, outcome: str) -> None:+ with turn.logical_llm_lock:+ for request_id in turn.logical_llm_calls:+ turn.logical_llm_outputs.setdefault(+ request_id,+ {"outcome": outcome},+ )+ self._drain_completed_logical_calls(turn, allow_orphan_drain=True)+@staticmethod- def _finish_logical_calls(turn: RelayTurnContext, *, outcome: str) -> None:+ def _drain_completed_logical_calls(+ turn: RelayTurnContext,+ *,+ operation_lease: RelayOperationLease | None = None,+ allow_orphan_drain: bool = False,+ ) -> None:lease = turn.leasehost = lease.live_runtime()- if host is None:+ session = lease.session+ if host is None or session is None:return- with turn.logical_llm_lock:- logical_calls = list(turn.logical_llm_calls.items())- turn.logical_llm_calls.clear()- while logical_calls:- _request_id, logical_handle = logical_calls[-1]- failure = host._close_scope_handle(- lease.session, logical_handle, output={"outcome": outcome},- failure_label="logical LLM scope close failed",- )- if failure is None:- logical_calls.pop()- continue+ while True:+ with turn.logical_llm_lock:+ if not turn.logical_llm_calls:+ turn.logical_llm_outputs.clear()+ return+ request_id = next(reversed(turn.logical_llm_calls))+ output = turn.logical_llm_outputs.get(request_id)+ if output is None:+ return+ logical_handle = turn.logical_llm_calls[request_id]+ if allow_orphan_drain:+ failure = host._close_scope_handle(+ session,+ logical_handle,+ output=output,+ failure_label="logical LLM scope close failed",+ )+ if failure is not None:+ logger.warning("Hermes Relay logical LLM finalization failed: %s", failure)+ return+ else:+ try:+ (operation_lease or host).run_in_session(+ session,+ pop_relay_scope,+ host.relay,+ logical_handle,+ output=output,+ metadata=runtime_metadata(host.runtime_id),+ )+ except Exception:+ # Provider results are authoritative. Retain the completion+ # so turn finalization can retry without changing the result.+ logger.warning("Hermes Relay logical LLM finalization failed", exc_info=True)+ returnwith turn.logical_llm_lock:- # Stack-owned: if the newest handle cannot close even after drain, older ones cannot either.- for pending_request_id, pending_handle in logical_calls:- turn.logical_llm_calls.setdefault(pending_request_id, pending_handle)- logger.warning("Hermes Relay logical LLM finalization failed: %s", failure)- break+ if turn.logical_llm_calls.get(request_id) is logical_handle:+ del turn.logical_llm_calls[request_id]+ turn.logical_llm_outputs.pop(request_id, None)@staticmethoddef _reset_turn_context(turn: RelayTurnContext) -> None:diff --git a/tests/hermes_cli/test_relay_shared_metrics_runtime.py b/tests/hermes_cli/test_relay_shared_metrics_runtime.pyindex 1af1455bf34..ee46ae3f3be 100644--- a/tests/hermes_cli/test_relay_shared_metrics_runtime.py+++ b/tests/hermes_cli/test_relay_shared_metrics_runtime.py@@ -1317,6 +1317,71 @@ def test_direct_runtime_fake_enforces_lifo_scope_contract(direct_runtime):runtime.run_in_session(session, direct_runtime.scope.pop, first)+def test_completed_logical_calls_close_in_stack_order(direct_runtime):+ coordinator = relay_runtime.SESSION_COORDINATOR+ profile_key = relay_runtime.current_profile_key()+ lease = coordinator.acquire_conversation(+ profile_key=profile_key,+ session_id="logical-completion-order",+ platform="cli",+ )+ turn = coordinator.begin_turn(+ lease,+ turn_id="turn",+ task_id="task",+ )+ runtime = lease.live_runtime()+ assert runtime is not None++ handles = []+ for request_id in ("request-1", "request-2"):+ handle = runtime.run_in_session(+ lease.session,+ direct_runtime.scope.push,+ relay_runtime.LOGICAL_LLM_SCOPE,+ direct_runtime.ScopeType.Function,+ handle=turn.handle,+ input={},+ )+ turn.logical_llm_calls[request_id] = handle+ handles.append(handle)++ coordinator.complete_logical_call(+ turn,+ request_id="request-1",+ handle=handles[0],+ output={"outcome": "success", "model": "auxiliary"},+ )+ assert list(turn.logical_llm_calls) == ["request-1", "request-2"]+ assert not [event for event in direct_runtime.events if event[0] == "scope.pop.rejected"]++ coordinator.complete_logical_call(+ turn,+ request_id="request-2",+ handle=handles[1],+ output={"outcome": "failed", "model": "primary"},+ )+ assert turn.logical_llm_calls == {}+ assert turn.logical_llm_outputs == {}+ logical_pops = [+ event+ for event in direct_runtime.events+ if event[0] == "scope.pop" and event[1] in handles+ ]+ assert [event[1] for event in logical_pops] == list(reversed(handles))+ assert [event[2]["output"] for event in logical_pops] == [+ {"outcome": "failed", "model": "primary"},+ {"outcome": "success", "model": "auxiliary"},+ ]++ coordinator.end_turn(turn, outcome="success")+ coordinator.release_conversation(lease)+ coordinator.finalize_conversation(+ profile_key=profile_key,+ session_id="logical-completion-order",+ )++def test_close_session_drains_orphaned_scopes_before_session_pop(direct_runtime):"""Orphaned physical scopes must not permanently wedge session close (#81521)."""runtime = relay_runtime.get_runtime()