The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): clarify prompt sends get the same ambiguous-timeout handling as approvals
Ben Barclaya7cfe391f731
diff --git a/gateway/run.py b/gateway/run.pyindex bcf991a9f4d..be4e2560b54 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -920,6 +920,36 @@ def _approval_send_outcome(future, timeout: float) -> str:return "sent" if getattr(result, "success", False) else "failed"+def _clarify_send_disposition(fut, *, session_key: str, clarify_mod) -> "str | None":+ """Decide whether a clarify prompt send aborts the wait, per the boundary rule.++ Same physics as the exec-approval card: the scheduling future can hit its+ deadline while the clarify card HAS already posted (late connector ack).+ Treating that timeout as a definitive failure cleared the session out from+ under a rendered card — the user answers a question whose registration is+ gone. Only a DEFINITIVE failure (error result / non-timeout exception /+ no future) tears down the registration and aborts; ``ambiguous`` keeps the+ registration armed and proceeds to the normal bounded wait, which already+ handles the truly-lost-card case via its response timeout.++ Returns the abort sentinel string on definitive failure, else ``None``+ (proceed to ``wait_for_response``).+ """+ outcome = _approval_send_outcome(fut, timeout=15)+ if outcome == "failed":+ # Couldn't deliver the prompt — clean up and return the sentinel so+ # the agent can fall back to a sensible default rather than hanging.+ logger.warning("Clarify send failed definitively; clearing registration")+ clarify_mod.clear_session(session_key)+ return "[clarify prompt could not be delivered]"+ if outcome == "ambiguous":+ logger.warning(+ "Clarify prompt send timed out — treating as possibly-delivered "+ "(no teardown; the registration stays armed for a late reply)"+ )+ return None++def _resolve_progress_thread_id(platform: Any,source_thread_id: Any,@@ -5936,7 +5966,6 @@ class TurnRunner:exc_info=True,)- send_ok = Falsefut = safe_schedule_threadsafe(ctx._status_adapter.send_clarify(chat_id=ctx._status_chat_id,@@ -5950,22 +5979,17 @@ class TurnRunner:logger=logger,log_message="Clarify send failed to schedule",)- if fut is None:- send_ok = False- else:- try:- result = fut.result(timeout=15)- send_ok = bool(getattr(result, "success", False))- except Exception as exc:- logger.warning("Clarify send failed: %s", exc)- send_ok = False-- if not send_ok:- # Couldn't deliver the prompt — clean up and return- # sentinel so the agent can fall back to a sensible- # default rather than hanging.- _clarify_mod.clear_session(ctx.session_key or "")- return "[clarify prompt could not be delivered]"+ # Boundary rule (see _approval_send_outcome): a send timeout is+ # AMBIGUOUS — the card may have posted with a late ack. Only a+ # definitive failure tears down the registration; ambiguous+ # falls through to the bounded wait so a late reply resolves.+ _abort = _clarify_send_disposition(+ fut,+ session_key=ctx.session_key or "",+ clarify_mod=_clarify_mod,+ )+ if _abort is not None:+ return _aborttimeout = _clarify_mod.get_clarify_timeout()response = _clarify_mod.wait_for_response(clarify_id, timeout=float(timeout))diff --git a/tests/gateway/test_clarify_send_timeout_ambiguity.py b/tests/gateway/test_clarify_send_timeout_ambiguity.pynew file mode 100644index 00000000000..27b5ddc8598--- /dev/null+++ b/tests/gateway/test_clarify_send_timeout_ambiguity.py@@ -0,0 +1,85 @@+"""Clarify prompt-send TIMEOUT must not tear down the registration.++Sibling of test_approval_send_timeout_ambiguity.py, same boundary rule, same+live physics: send_clarify's scheduling future can hit its 15s deadline while+the clarify card HAS already posted (late connector ack). The old caller+treated any exception — including the timeout — as a definitive failure and+ran clear_session(), so the user answered a rendered card whose registration+was already gone.++Contract under test: TimeoutError is AMBIGUOUS (possibly delivered) — the+registration must stay armed (clear_session NOT called) and the caller must+proceed to the bounded wait (disposition None). A definitive error+(SendResult success=False, non-timeout exception, or no future) keeps+today's teardown + sentinel behavior.+"""++import concurrent.futures+from unittest.mock import MagicMock++from gateway.run import _clarify_send_disposition++SENTINEL = "[clarify prompt could not be delivered]"+++class _Result:+ def __init__(self, success, error=None):+ self.success = success+ self.error = error+++def test_timeout_keeps_registration_armed_and_proceeds_to_wait():+ fut = MagicMock()+ fut.result.side_effect = concurrent.futures.TimeoutError()+ clarify_mod = MagicMock()+ disposition = _clarify_send_disposition(+ fut, session_key="sk", clarify_mod=clarify_mod+ )+ assert disposition is None, (+ "a send timeout aborted the clarify wait — this is the "+ "cleared-session-under-a-rendered-card bug (card posted, ack late); "+ "ambiguous must fall through to wait_for_response"+ )+ clarify_mod.clear_session.assert_not_called()+++def test_successful_send_proceeds_to_wait():+ fut = MagicMock()+ fut.result.return_value = _Result(True)+ clarify_mod = MagicMock()+ assert (+ _clarify_send_disposition(fut, session_key="sk", clarify_mod=clarify_mod)+ is None+ )+ clarify_mod.clear_session.assert_not_called()+++def test_definitive_error_result_tears_down_and_aborts():+ fut = MagicMock()+ fut.result.return_value = _Result(False, "relay prompt op unavailable")+ clarify_mod = MagicMock()+ assert (+ _clarify_send_disposition(fut, session_key="sk", clarify_mod=clarify_mod)+ == SENTINEL+ )+ clarify_mod.clear_session.assert_called_once_with("sk")+++def test_non_timeout_exception_tears_down_and_aborts():+ fut = MagicMock()+ fut.result.side_effect = RuntimeError("loop unavailable")+ clarify_mod = MagicMock()+ assert (+ _clarify_send_disposition(fut, session_key="sk", clarify_mod=clarify_mod)+ == SENTINEL+ )+ clarify_mod.clear_session.assert_called_once_with("sk")+++def test_missing_future_tears_down_and_aborts():+ clarify_mod = MagicMock()+ assert (+ _clarify_send_disposition(None, session_key="sk", clarify_mod=clarify_mod)+ == SENTINEL+ )+ clarify_mod.clear_session.assert_called_once_with("sk")