From a7cfe391f7317366face6eb9bcf106da65c7fdc6 Mon Sep 17 00:00:00 2001 From: Ben Barclay Date: Fri, 21 Aug 2026 07:53:21 +1000 Subject: [PATCH] fix(gateway): clarify prompt sends get the same ambiguous-timeout handling as approvals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The clarify caller treated a send-scheduling timeout as a definitive failure: clear_session() + '[clarify prompt could not be delivered]'. Same physics as the approval card fixed earlier in this PR — the card may well have posted with a late connector ack — so the teardown ran out from under a rendered clarify card and the user's answer resolved nothing. New _clarify_send_disposition() routes the outcome through _approval_send_outcome: only a DEFINITIVE failure (error result, non-timeout exception, no future) clears the registration and aborts; ambiguous logs a warning and falls through to wait_for_response, whose existing bounded wait already handles the truly-lost-card case. This makes the boundary rule stated in the ambiguity test docstring hold for the clarify lane, not just approvals. Tests: 5 disposition tests mirroring the approval suite, including clear_session-not-called on timeout. Mutation-verified: folding ambiguous into the failed branch sends test_timeout_keeps_registration_armed_and_proceeds_to_wait red. Relay + gateway sweep 283/283. --- gateway/run.py | 58 +++++++++---- .../test_clarify_send_timeout_ambiguity.py | 85 +++++++++++++++++++ 2 files changed, 126 insertions(+), 17 deletions(-) create mode 100644 tests/gateway/test_clarify_send_timeout_ambiguity.py diff --git a/gateway/run.py b/gateway/run.py index bcf991a9f4..be4e2560b5 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 = False fut = 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 _abort timeout = _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.py new file mode 100644 index 0000000000..27b5ddc859 --- /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")