Skip to content

The agent that grows with you

fix(clarify): preserve resolved answers when clear_session races a button response

David Metcalfeebb28591325d
diff --git a/tests/tools/test_clarify_gateway.py b/tests/tools/test_clarify_gateway.py
index a0e7722d742..e9d410fb573 100644
--- a/tests/tools/test_clarify_gateway.py
+++ b/tests/tools/test_clarify_gateway.py
@@ -92,6 +92,34 @@ class TestClarifyPrimitive:
assert result == ""
+ def test_clear_session_preserves_resolved_response(self):
+ """clear_session must not clobber an answer that already won.
+
+ First-writer-wins (doryani-ai on PR #75732): a button callback that
+ resolved the entry before session cleanup must keep its response.
+ clear_session only cancels entries whose event is not yet set, so
+ the racing waiter observes the real answer, not the empty sentinel.
+ """
+ from tools import clarify_gateway as cm
+
+ cm.register("id-race", "sk-race", "Pick one", ["A", "B"])
+
+ def waiter():
+ return cm.wait_for_response("id-race", timeout=10.0)
+
+ with ThreadPoolExecutor(1) as pool:
+ fut = pool.submit(waiter)
+ time.sleep(0.05)
+ # Button wins the race first...
+ assert cm.resolve_gateway_clarify("id-race", "B") is True
+ # ...then session cleanup runs before the waiter wakes.
+ cancelled = cm.clear_session("sk-race")
+ assert cancelled == 0
+ result = fut.result(timeout=10.0)
+ # The real answer must survive cleanup, not the "" cancellation.
+ assert result == "B"
+
+
def test_notify_register_unregister_clears_pending(self):
"""unregister_notify cancels any pending clarify so threads unwind."""
from tools import clarify_gateway as cm
diff --git a/tools/clarify_gateway.py b/tools/clarify_gateway.py
index c88ef2f45dc..6bee2214bce 100644
--- a/tools/clarify_gateway.py
+++ b/tools/clarify_gateway.py
@@ -372,22 +372,39 @@ def clear_session(session_key: str) -> int:
Used by session-boundary cleanup (e.g. ``/new``, gateway shutdown,
cached-agent eviction) so blocked agent threads don't hang past the
- end of their session. Returns the number of entries cancelled.
+ end of their session. Returns the number of entries actually
+ cancelled (i.e. whose event had not yet been set). Already-resolved
+ entries are dropped from the registry but their response is preserved.
+
+ First-writer-wins: an entry whose event is already set has been resolved
+ by a real response (button callback or text intercept). Session cleanup
+ must NOT overwrite that response with the empty cancellation sentinel —
+ the waiting agent thread would observe a cancelled prompt even though the
+ user answered. Only unresolved entries are cancelled here.
"""
with _lock:
ids = list(_session_index.pop(session_key, []) or [])
entries = [_entries.pop(cid, None) for cid in ids]
- cancelled = 0
- for entry in entries:
- if entry is None:
- continue
- # Empty string sentinel — agent code can distinguish from a real
- # response by inspecting the wait_for_response return value
- # alongside its own timeout deadline. Most callers just treat any
- # falsy result as "user did not respond".
- entry.response = ""
- entry.event.set()
- cancelled += 1
+ # The mutation loop must stay inside the lock: the pop above and the
+ # event.is_set() check below have to be atomic with respect to
+ # resolve_gateway_clarify, or a button callback could win between the
+ # pop and the check and have its answer clobbered by the sentinel.
+ cancelled = 0
+ for entry in entries:
+ if entry is None:
+ continue
+ # Entry is removed from the global registry regardless of its
+ # state — a cleared session must not be resurrected by late
+ # callbacks — but a resolved entry keeps its real response.
+ if entry.event.is_set():
+ continue
+ # Empty string sentinel — agent code can distinguish from a real
+ # response by inspecting the wait_for_response return value
+ # alongside its own timeout deadline. Most callers just treat any
+ # falsy result as "user did not respond".
+ entry.response = ""
+ entry.event.set()
+ cancelled += 1
return cancelled