Skip to content

The agent that grows with you

fix(approval): coalesced followers wake when the leader prompt dies

Maciej Lisiewskia86d004f3517
diff --git a/tests/tools/test_approval_gateway_wait_coalesce_race.py b/tests/tools/test_approval_gateway_wait_coalesce_race.py
new file mode 100644
index 00000000000..ce277431254
--- /dev/null
+++ b/tests/tools/test_approval_gateway_wait_coalesce_race.py
@@ -0,0 +1,106 @@
+"""Coalesced gateway approvals under concurrent leader/follower threads.
+
+Identical concurrent approvals share ONE prompt: the first caller (leader) enqueues and notifies, later
+callers (followers) wait on the leader's event and adopt its outcome. These tests force the interleavings
+where the leader's prompt goes away without an answer and where two identical requests race to lead.
+"""
+
+import threading
+
+from tools import approval as mod
+from tools import approval_gateway_wait as wait_mod
+
+
+SESSION_KEY = "approval-coalesce-race"
+APPROVAL = {"command": "rm -rf build", "description": "d", "pattern_key": "dangerous", "pattern_keys": ["dangerous"]}
+# Long enough that a follower left waiting on a dead leader is unmistakable; the tests release it on failure.
+APPROVAL_TIMEOUT = 60
+
+
+def _clear():
+ mod._gateway_queues.clear()
+ mod._gateway_notify_cbs.clear()
+
+
+def _leader_never_polls(follower_waiting):
+ raise AssertionError("the leader's notify failed; it must not wait")
+
+
+def _run_leader_then_follower(monkeypatch, notify_cb, *, leader_poll=_leader_never_polls):
+ """Start a leader, then a follower that coalesces onto it; *leader_poll* decides how the leader's own
+ wait ends once the follower is blocked on the leader's event. Returns (results, follower, release) —
+ ``release()`` frees a follower still blocked on the leader's (already dequeued) entry."""
+ monkeypatch.setattr(wait_mod._ctx, "_fire_approval_hook", lambda name, **kw: None)
+ monkeypatch.setattr(wait_mod._ctx, "_get_approval_timeout", lambda: APPROVAL_TIMEOUT)
+ real_poll = wait_mod._poll_event
+ follower_waiting = threading.Event()
+ leader_enqueued = threading.Event()
+ results: dict = {}
+
+ def poll(event, session_key, *, interrupt_log):
+ if "Coalesced" in interrupt_log:
+ follower_waiting.set()
+ return real_poll(event, session_key, interrupt_log=interrupt_log)
+ return leader_poll(follower_waiting)
+
+ monkeypatch.setattr(wait_mod, "_poll_event", poll)
+
+ def leader_notify(data):
+ results["leader_entry"] = mod._gateway_queues[SESSION_KEY][0]
+ leader_enqueued.set()
+ notify_cb(data, follower_waiting)
+
+ def run(name, cb):
+ results[name] = wait_mod._await_gateway_decision(SESSION_KEY, cb, dict(APPROVAL))
+
+ leader = threading.Thread(target=run, args=("leader", leader_notify), daemon=True)
+ leader.start()
+ assert leader_enqueued.wait(10)
+ follower = threading.Thread(target=run, args=("follower", lambda data: None), daemon=True)
+ follower.start()
+ leader.join(10)
+ assert not leader.is_alive()
+
+ def release():
+ results["leader_entry"].event.set()
+ follower.join(10)
+
+ return results, follower, release
+
+
+def test_follower_adopts_the_leaders_timeout_instead_of_hanging(monkeypatch):
+ _clear()
+
+ def leader_times_out(follower_waiting):
+ assert follower_waiting.wait(10)
+ return "timeout"
+
+ results, follower, release = _run_leader_then_follower(
+ monkeypatch, lambda data, follower_waiting: None, leader_poll=leader_times_out)
+ follower.join(10)
+ alive = follower.is_alive()
+ release()
+ assert not alive, "follower still blocked after the leader's prompt expired"
+ assert results["leader"] == {"resolved": False, "choice": None, "reason": None}
+ assert results["follower"] == {"resolved": False, "choice": None, "reason": None, "coalesced": True}
+ # No prompt is left pending for a late /approve to be told "ok" about.
+ assert mod.resolve_gateway_approval(SESSION_KEY, "once") == 0
+
+
+def test_follower_wakes_when_the_leaders_notify_fails(monkeypatch):
+ _clear()
+
+ def notify_fails_after_follower_joined(data, follower_waiting):
+ assert follower_waiting.wait(10)
+ raise RuntimeError("platform send failed")
+
+ results, follower, release = _run_leader_then_follower(monkeypatch, notify_fails_after_follower_joined)
+ follower.join(10)
+ alive = follower.is_alive()
+ release()
+ assert not alive, "follower still blocked after the leader's prompt could not be delivered"
+ assert results["leader"] == {"resolved": False, "choice": None, "notify_failed": True}
+ decision = results["follower"]
+ assert decision["resolved"] is False and decision["choice"] is None and decision["coalesced"] is True
+ # Never delivered, so it is a withdrawal — not a user deny and not a silent timeout.
+ assert decision["cancelled"]
diff --git a/tools/approval_gateway_wait.py b/tools/approval_gateway_wait.py
index ea6cef0b8fd..e6c81b2992c 100644
--- a/tools/approval_gateway_wait.py
+++ b/tools/approval_gateway_wait.py
@@ -24,7 +24,7 @@ logger = logging.getLogger("tools.approval")
class _ApprovalEntry:
"""One pending dangerous-command approval inside a gateway session."""
- __slots__ = ("acknowledged", "cancelled", "data", "event", "reason", "result", "settle")
+ __slots__ = ("acknowledged", "cancelled", "data", "event", "expired", "reason", "result", "settle")
def __init__(self, data: dict):
self.event = threading.Event()
@@ -40,6 +40,8 @@ class _ApprovalEntry:
# Why the prompt was withdrawn with nobody answering (interrupt cause, session teardown);
# followers and teardown read it so a withdrawn prompt never renders as a user deny.
self.cancelled: str | None = None
+ # The prompt timed out unanswered; followers woken by its event adopt that timeout.
+ self.expired = False
def _poll_event(event: threading.Event, session_key: str, *, interrupt_log: str) -> str:
@@ -114,6 +116,8 @@ def _await_coalesced_leader(session_key: str, leader, payload: dict):
state = _poll_event(leader.event, session_key,
interrupt_log="Coalesced approval wait interrupted — "
"returning deny for session %s")
+ if state == "set" and leader.result is None and leader.expired:
+ state = "timeout"
cancelled = _cancel_cause(state, leader)
if state == "interrupted":
# Deny only OUR follower; the leader thread handles its own signal.
@@ -183,6 +187,13 @@ def _await_gateway_decision(session_key: str, notify_cb, approval_data: dict, *,
if not queue:
_approval._gateway_queues.pop(session_key, None)
settle, entry.settle = entry.settle, None
+ if choice is None and state in ("timeout", "notify_failed"):
+ # Coalesced followers block on this event: wake them with the leader's outcome rather than
+ # leaving them waiting their own full timeout on a prompt that no longer exists.
+ entry.expired = state == "timeout"
+ if state == "notify_failed":
+ entry.cancelled = "the approval prompt could not be delivered"
+ entry.event.set()
if settle is not None:
# ``request.cancel`` carries a RequestCancelReason: a choice committed from another surface is
# ``resolved``; a withdrawn entry (woken with no choice — session torn down, turn ended, client