Skip to content

The agent that grows with you

fix(streaming): widen #81521 interrupt join to sibling paths and use version-correct Relay top accessor

Teknium3537ef9d015e
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index 4a15d2f62d9..98d5ceb83cb 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -1721,6 +1721,18 @@ def interruptible_api_call(agent, api_kwargs: dict):
_close_request_client_once("interrupt_abort")
except Exception:
pass
+ # #81521 (sibling of the streaming-path fix): wait for the worker
+ # to unwind Relay-managed scopes before surfacing
+ # InterruptedError, so turn teardown cannot race a still-open
+ # physical scope and corrupt the LIFO stack.
+ t.join(timeout=2.0)
+ if t.is_alive():
+ logger.warning(
+ "Non-streaming worker still alive after interrupt abort "
+ "(%.1fs join timeout); Relay teardown will best-effort "
+ "drain orphaned scopes (#81521).",
+ 2.0,
+ )
raise InterruptedError("Agent interrupted during API call")
if result["error"] is not None:
raise result["error"]
@@ -3411,6 +3423,19 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta=
while t.is_alive():
t.join(timeout=0.3)
if agent._interrupt_requested:
+ # #81521 (sibling of the main streaming-path fix): give
+ # the Bedrock worker a bounded window to unwind its
+ # Relay-managed stream scopes before surfacing
+ # InterruptedError, so turn teardown cannot race a
+ # still-open physical scope and corrupt the LIFO stack.
+ t.join(timeout=2.0)
+ if t.is_alive():
+ logger.warning(
+ "Bedrock streaming worker still alive after "
+ "interrupt (%.1fs join timeout); Relay teardown "
+ "will best-effort drain orphaned scopes (#81521).",
+ 2.0,
+ )
raise InterruptedError("Agent interrupted during Bedrock API call")
# Liveness watchdog: no Bedrock event for longer than the stale
# timeout means the stream has wedged (open socket, keep-alives but
diff --git a/agent/relay_runtime.py b/agent/relay_runtime.py
index ec7d0162725..76e4079809a 100644
--- a/agent/relay_runtime.py
+++ b/agent/relay_runtime.py
@@ -573,6 +573,20 @@ class RelayRuntime:
def close_with_drain() -> None:
def current_top() -> Any:
+ # Version-correct accessor first: the pinned nemo-relay
+ # binding exposes ``scope.get_handle()`` returning the
+ # current top-of-stack ScopeHandle. Its
+ # ``get_scope_stack()`` returns a native ScopeStack object
+ # that ``scope.pop`` rejects with TypeError, so it must
+ # never be treated as a handle (#81601 review).
+ get_handle = getattr(
+ getattr(self.relay, "scope", None), "get_handle", None
+ )
+ if callable(get_handle):
+ try:
+ return get_handle()
+ except Exception:
+ pass
top = self.relay.get_scope_stack()
# Some Relay builds return the live stack (list). Others
# return the top handle directly — including tuple handles
@@ -582,6 +596,18 @@ class RelayRuntime:
return top[-1] if top else None
return top
+ def same_handle(a: Any, b: Any) -> bool:
+ # Native ScopeHandle instances do not implement __eq__ by
+ # value — two handles for the same scope compare unequal —
+ # so compare by uuid when both sides expose one.
+ if a is None or b is None:
+ return a is b
+ if a is b or a == b:
+ return True
+ a_uuid = getattr(a, "uuid", None)
+ b_uuid = getattr(b, "uuid", None)
+ return a_uuid is not None and a_uuid == b_uuid
+
try:
self.relay.scope.pop(
handle,
@@ -594,12 +620,12 @@ class RelayRuntime:
for _ in range(drain_limit):
top = current_top()
- if top is None or top == handle:
+ if top is None or same_handle(top, handle):
break
# Never pop the session root while draining for a nested handle.
if (
session_root is not None
- and top == session_root
+ and same_handle(top, session_root)
and handle is not session_root
):
break
diff --git a/tests/hermes_cli/test_relay_shared_metrics_runtime.py b/tests/hermes_cli/test_relay_shared_metrics_runtime.py
index 629afe79c7d..998fae07b2b 100644
--- a/tests/hermes_cli/test_relay_shared_metrics_runtime.py
+++ b/tests/hermes_cli/test_relay_shared_metrics_runtime.py
@@ -1346,6 +1346,45 @@ def test_close_session_drains_orphaned_scopes_before_session_pop(direct_runtime)
assert session_pops, f"session scope never closed (rejected={rejected!r})"
+def test_real_binding_drains_orphaned_scope_before_session_pop(
+ real_binding_runtime,
+):
+ """Orphan drain must work against the pinned native binding (#81521).
+
+ Regression guard for the #81601 review finding: the native binding's
+ ``get_scope_stack()`` returns a ``ScopeStack`` object (not a list and
+ not a ``ScopeHandle``), and ``scope.pop`` rejects it with TypeError.
+ The drain path must use the version-correct top accessor
+ (``scope.get_handle()``) and compare handles by uuid, because native
+ ``ScopeHandle`` instances do not compare equal by value.
+ """
+ runtime = relay_runtime.get_runtime()
+ assert runtime is not None
+ session = runtime.ensure_session({"session_id": "native-orphan-drain"})
+ assert session is not None
+
+ orphan = runtime.run_in_session(
+ session,
+ real_binding_runtime.scope.push,
+ "orphaned-physical-llm",
+ real_binding_runtime.ScopeType.Function,
+ handle=session.handle,
+ )
+ assert orphan is not None
+
+ # Without the drain fix this fails: the direct session pop raises
+ # "scope handle is not at the top of the stack", and the pre-fix
+ # drain retried with a ScopeStack object that pop() rejects.
+ failure = runtime._close_scope_handle(
+ session,
+ session.handle,
+ output={},
+ allow_closing=True,
+ failure_label="session scope close failed",
+ )
+ assert failure is None, failure
+
+
def test_concurrent_turn_skips_relay_before_scope_stack_can_interleave(
direct_runtime,
):