Skip to content

The agent that grows with you

fix(bot-mode): bound the live DM wait and check the owner with the claim's own match

Brooklyn Nicholsona6509d6b8fd3
diff --git a/tests/tools/test_bot_mode_dm.py b/tests/tools/test_bot_mode_dm.py
index d5565a9258f..d112a389a62 100644
--- a/tests/tools/test_bot_mode_dm.py
+++ b/tests/tools/test_bot_mode_dm.py
@@ -712,59 +712,23 @@ def test_live_dm_wait_rechecks_receipt_when_owner_disappears_at_claim(tmp_path,
assert notice["reply"] == "PONG"
-def test_live_dm_wait_does_not_cancel_a_claim_after_the_last_read(tmp_path, monkeypatch, capsys):
- from tools import bot_live_delivery as live
-
- owner = dict(profile_home=str(tmp_path), session_id="bot", lease_id="lease", live_session_id="live")
- record = live.deliver_to_live_owner(tmp_path, owner, "ping", delivery_id="2" * 32)
- monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_SECONDS", 0.01)
- monkeypatch.setattr(live, "_POLL_SECONDS", 0.01)
- owner_checked = False
-
- def owner_gone(_home):
- nonlocal owner_checked
- owner_checked = True
- return None
-
- monkeypatch.setattr(live, "find_canonical_live_owner", owner_gone)
- original_read = live.read_delivery_result
- claimed_during_read = False
-
- def read_then_claim(home, delivery_id):
- nonlocal claimed_during_read
- snapshot = original_read(home, delivery_id)
- assert snapshot is not None
- if owner_checked and snapshot["status"] == "queued" and not claimed_during_read:
- claimed_during_read = True
- claimed = live.claim_pending_delivery(tmp_path, owner)
- assert claimed is not None
- live.complete_delivery(tmp_path, delivery_id, status="settled", reply="PONG")
- return snapshot
-
- monkeypatch.setattr(live, "read_delivery_result", read_then_claim)
- assert bot_mode_dm._wait_live_dm(str(tmp_path), record["delivery_id"]) == 0
- notice = json.loads(capsys.readouterr().out)
- assert claimed_during_read
- assert notice["status"] == "settled"
- assert notice["reply"] == "PONG"
-
-
def test_live_dm_wait_keeps_claimed_turn_until_it_settles(tmp_path, monkeypatch, capsys):
+ """An owner gone after its claim still gets one more window to settle the in-flight turn."""
from tools import bot_live_delivery as live
owner = dict(profile_home=str(tmp_path), session_id="bot", lease_id="lease", live_session_id="live")
record = live.deliver_to_live_owner(tmp_path, owner, "ping", delivery_id="d" * 32)
assert live.claim_pending_delivery(tmp_path, owner) is not None
- monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_SECONDS", 0.03)
+ monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_SECONDS", 0.5)
monkeypatch.setattr(live, "_POLL_SECONDS", 0.01)
- monkeypatch.setattr(live, "find_canonical_live_owner", lambda h: None)
+ settling = threading.Timer(0.02, lambda: live.complete_delivery(
+ tmp_path, record["delivery_id"], status="settled", reply="PONG"))
- def settle_later():
- time.sleep(0.05)
- live.complete_delivery(tmp_path, record["delivery_id"], status="settled", reply="PONG")
+ def owner_gone_then_settle(_home):
+ settling.start()
+ return None
- settling = threading.Thread(target=settle_later)
- settling.start()
+ monkeypatch.setattr(live, "find_canonical_live_owner", owner_gone_then_settle)
try:
exit_code = bot_mode_dm._wait_live_dm(str(tmp_path), record["delivery_id"])
finally:
@@ -804,6 +768,46 @@ def test_live_dm_wait_releases_claimed_runner_after_owner_is_gone(tmp_path, monk
assert final is not None and final["status"] == "claimed"
[email protected]("status", ["queued", "claimed"])
+def test_live_dm_wait_releases_runner_when_owner_lookup_keeps_failing(tmp_path, monkeypatch, capsys, status):
+ """A lookup that always raises is an owner that cannot be confirmed: bounded, never cancelled."""
+ from tools import bot_live_delivery as live
+
+ owner = dict(profile_home=str(tmp_path), session_id="bot", lease_id="lease", live_session_id="live")
+ record = live.deliver_to_live_owner(tmp_path, owner, "ping", delivery_id="2" * 32)
+ if status == "claimed":
+ assert live.claim_pending_delivery(tmp_path, owner) is not None
+ monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_SECONDS", 0.01)
+ monkeypatch.setattr(live, "_POLL_SECONDS", 0.01)
+
+ def lookup_fails(_home):
+ raise OSError("registry locked")
+
+ monkeypatch.setattr(live, "find_canonical_live_owner", lookup_fails)
+ assert bot_mode_dm._wait_live_dm(str(tmp_path), record["delivery_id"]) == 0
+ notice = json.loads(capsys.readouterr().out)
+ assert notice["status"] == status
+ assert "Do not resend" in notice["detail"]
+ assert live.read_delivery_result(tmp_path, record["delivery_id"])["status"] == status
+
+
+def test_live_dm_wait_stops_at_its_deadline_while_the_owner_holds_the_receipt(tmp_path, monkeypatch, capsys):
+ """A live owner that never claims (stalled consumer) or never settles still releases the runner."""
+ from tools import bot_live_delivery as live
+
+ owner = dict(profile_home=str(tmp_path), session_id="bot", lease_id="lease", live_session_id="live")
+ record = live.deliver_to_live_owner(tmp_path, owner, "ping", delivery_id="3" * 32)
+ monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_SECONDS", 0.01)
+ monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_MAX_SECONDS", 0.1)
+ monkeypatch.setattr(live, "_POLL_SECONDS", 0.01)
+ monkeypatch.setattr(live, "find_canonical_live_owner", lambda h: owner)
+
+ assert bot_mode_dm._wait_live_dm(str(tmp_path), record["delivery_id"]) == 0
+ notice = json.loads(capsys.readouterr().out)
+ assert notice["status"] == "queued"
+ assert "Do not resend" in notice["detail"]
+
+
# ── plaintext tempfile lifecycle ─────────────────────────────────────────────
diff --git a/tools/bot_live_delivery.py b/tools/bot_live_delivery.py
index ecb64c1625b..2fac2a9c183 100644
--- a/tools/bot_live_delivery.py
+++ b/tools/bot_live_delivery.py
@@ -240,6 +240,12 @@ def _matches(home: Path | str, record: dict, owner: dict) -> bool:
db.close()
+def owner_holds_delivery(profile_home: Path | str, record: dict) -> bool:
+ """Whether the canonical live owner is still one that could claim ``record``."""
+ owner = find_canonical_live_owner(profile_home)
+ return owner is not None and _matches(profile_home, record, owner)
+
+
def claim_pending_delivery(
profile_home: Path | str, owner: dict[str, Any],
) -> dict[str, Any] | None:
diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.py
index e11dffbad4d..e807596a9a7 100644
--- a/tools/bot_mode_dm.py
+++ b/tools/bot_mode_dm.py
@@ -49,6 +49,9 @@ REPLY_COMPLETION_CHARS = MESSAGE_MAX_CHARS + 2000
_DM_DIR_NAME = "hermes-dm"
_DM_STALE_SECONDS = 24 * 60 * 60
_LIVE_WAIT_SECONDS = 300
+# A live owner may run a turn past one wait window, but each waiting runner holds ~46 MB and the
+# sender's notify slot: past this the runner reports pending (do not resend) and exits.
+_LIVE_WAIT_MAX_SECONDS = 30 * 60
# '<peer>/<agent>' — peer names are lowercase (``hermes peer`` normalizes them).
_PEER_TARGET_RE = re.compile(r"^([a-z0-9][a-z0-9_-]{0,63})/([a-zA-Z0-9][a-zA-Z0-9_-]{0,63})$")
@@ -519,31 +522,23 @@ def _admit_live_dm(profile_home: Path | None, dm_file: str, author: Optional[dic
def _wait_live_dm(home: str, delivery_id: str, *, dm_file: "str | os.PathLike | None" = None) -> int:
from tools.bot_failure_reasons import RUNTIME_OFFLINE
- from tools.bot_live_delivery import (await_delivery, cancel_queued_delivery,
- find_canonical_live_owner, read_delivery_result)
+ from tools.bot_live_delivery import await_delivery, cancel_queued_delivery, owner_holds_delivery
- owner_missing_claimed = False
+ deadline = time.monotonic() + _LIVE_WAIT_MAX_SECONDS
+ missed = 0
while True:
- record = await_delivery(home, delivery_id, _LIVE_WAIT_SECONDS)
- if record is None or record["status"] not in ("queued", "claimed"):
+ record = await_delivery(home, delivery_id, max(0.0, min(_LIVE_WAIT_SECONDS, deadline - time.monotonic())))
+ if record is None or record["status"] not in ("queued", "claimed") or time.monotonic() >= deadline:
break
try:
- owner = find_canonical_live_owner(home)
+ held = owner_holds_delivery(home, record)
except Exception:
- logger.debug("Could not check live DM owner; keep waiting for receipt", exc_info=True)
+ logger.debug("Could not check live DM owner", exc_info=True)
+ held = None
+ if held:
+ missed = 0
continue
- pinned = record["owner"]
- if owner is not None and all(owner[key] == pinned[key] for key in
- ("profile_home", "lease_id", "live_session_id")):
- owner_missing_claimed = False
- continue
- # A claim or settlement can race the owner lookup. Decide from a fresh
- # receipt so the runner cannot exit on a stale queued snapshot.
- record = read_delivery_result(home, delivery_id)
- if record is None or record["status"] not in ("queued", "claimed"):
- break
- if record["status"] == "queued":
- # The consumer may still have a captured owner and race this read.
+ if held is False and record["status"] == "queued":
# Under the same mailbox lock as claim, either cancellation wins or
# the claim wins and we must keep waiting for its outcome.
record = cancel_queued_delivery(
@@ -551,13 +546,13 @@ def _wait_live_dm(home: str, delivery_id: str, *, dm_file: "str | os.PathLike |
reason=RUNTIME_OFFLINE)
if record is None or record["status"] != "claimed":
break
- owner_missing_claimed = False
+ missed = 0
continue
- if owner_missing_claimed:
- # A vanished consumer may leave a permanent claim. Allow one more
- # wait window for an in-flight turn to settle, then release the runner.
+ # A vanished consumer may leave a permanent claim, and an owner we cannot look up
+ # may be gone: allow one more window for an in-flight turn, then release the runner.
+ missed += 1
+ if missed > 1:
break
- owner_missing_claimed = True
status = record["status"] if record else "ambiguous"
payload = {key: record[key] for key in ("reply", "error", "reason") if record and record.get(key)}
payload.update(status=status, delivery_id=delivery_id)