fix(bots): a waiting Bot DM sender keeps its reply across an owner restart
`await_delivery` (local `message_agent`, the Desktop relay's legacy lane, `hermes peer dm/run` without an in-process authority) re-read the receipt through `read_delivery_result`, which replays the whole envelope as a `bot_relay.deliver` RPC: endpoint discovery, a control-socket ticket and a fresh websocket on every 0.5 s tick, up to ~3,600 handshakes per 30-minute wait. While the owner restarted, discovery raised "profile authority is not ready" straight out of the loop, so the sender lost a reply the restarted owner later produced (live probe: the wait died 0.02 s after the kill). Waiters now poll the receipt file the owner already publishes when an admission settles and again at startup recovery (`_poll_receipt`); a restart is just a longer pending stretch. `read_delivery_result` keeps the replay for producers that re-confirm their admission (cron, DM intents). For the file to be a complete answer the owner publishes what the RPC used to compute: the admission's status right after it commits (not the bare `canonical` marker), a failed original whose one transient retry is still due as interim `claimed` (never the final `failed`), and the final `failed` once that retry is refused. Startup recovery re-arms the watch on the live admission or admits the pending retry through the same predicate the peer waiter uses, so a retry deferred by a draining owner is admitted by its successor and the same wait gets the answer. Live (real `gateway.run` daemon, loopback model): a 3 s wait went from 7 authority RPCs to 0; a wait across kill + 3 s down + restart now returns `settled` / `AUTOMATION_ACK` instead of raising. Review: https://github.com/NousResearch/hermes-agent/pull/106742 (itsflownium review: receipt read is a full authority RPC polled every 0.5 s and raises through transient restarts, tools/bot_live_delivery.py:316-357)
This commit is contained in:
@@ -13,7 +13,7 @@ from gateway.session_contract import Principal, SessionRef
|
||||
from gateway.config import Platform
|
||||
from gateway.platforms.event import MessageEvent
|
||||
from hermes_state_runtime import RuntimeStoreError, get_session_admission
|
||||
from tools.bot_live_delivery import _delivery_id, _locked, _read, _write
|
||||
from tools.bot_live_delivery import _delivery_id, _locked, _read, _root, _write
|
||||
|
||||
|
||||
_CANONICAL_RECEIPT_STATUSES = frozenset({
|
||||
@@ -164,6 +164,10 @@ def _result(authority, record):
|
||||
status, reply = _admission_outcome(authority, retry_id)
|
||||
else:
|
||||
status, reply = _admission_outcome(authority, record['admission_id'], record)
|
||||
if status == 'failed' and _retry_due(authority, record):
|
||||
# Interim, never the answer: the one retry is admitted next (or by the restarted
|
||||
# owner's recovery while this one drains). Senders poll the published receipt file.
|
||||
status = 'claimed'
|
||||
error = reason = None
|
||||
if status == 'failed':
|
||||
error, reason = _failure(authority, current)
|
||||
@@ -190,20 +194,26 @@ def peer_wait_admission(authority, record):
|
||||
An original that failed while its one retry is still eligible is ``interim``: pending, never
|
||||
the answer, while the owner's receipt task admits the retry (or records why it would not;
|
||||
the receipt file is re-read for that, the caller's in-memory record is stale)."""
|
||||
from tools.bot_live_delivery import _read, _root
|
||||
retry_id = _retry_admission(authority, record)
|
||||
if retry_id:
|
||||
return (retry_id, False) if _admission_outcome(authority, retry_id)[0] in {'queued', 'claimed'} else (None, False)
|
||||
status = _admission_outcome(authority, record['admission_id'], record)[0]
|
||||
if status in {'queued', 'claimed'}:
|
||||
return record['admission_id'], False
|
||||
if status == 'failed':
|
||||
saved = _read(_root(record['profile_home']) / f"{record['delivery_id']}.json") or record
|
||||
if _retry_eligible(authority, {**record, 'retry': saved.get('retry')}):
|
||||
return record['admission_id'], True
|
||||
if status == 'failed' and _retry_due(authority, record):
|
||||
return record['admission_id'], True
|
||||
return None, False
|
||||
|
||||
|
||||
def _retry_due(authority, record):
|
||||
"""The failed original's one retry is still to be admitted. Its refusal is recorded on the
|
||||
receipt file; an in-memory record without the ``retry`` marker re-reads it there."""
|
||||
retry = record.get('retry')
|
||||
if retry is None:
|
||||
retry = (_read(_root(record['profile_home']) / f"{record['delivery_id']}.json") or {}).get('retry')
|
||||
return _retry_eligible(authority, {**record, 'retry': retry})
|
||||
|
||||
|
||||
def _retry_identity(key):
|
||||
return 'bot:' + key + ':retry'
|
||||
|
||||
@@ -254,6 +264,7 @@ async def _maybe_retry(authority, home, path, record):
|
||||
if exc.reason == 'runtime_draining':
|
||||
return # nothing recorded: the restarted owner's recovery re-evaluates the same gate
|
||||
record['retry'] = {'identity': identity, 'refused': exc.reason}
|
||||
record.update(_result(authority, record)) # the refusal makes the original's failure final
|
||||
_write(path, record)
|
||||
return
|
||||
event = MessageEvent(text=record['message'], source=live.source, internal=True,
|
||||
@@ -342,9 +353,9 @@ async def recover_bot_deliveries(authority):
|
||||
continue
|
||||
record.update(_result(authority, record))
|
||||
_write(path, record)
|
||||
if record['status'] in {'queued', 'claimed'}:
|
||||
_watch_reply(authority, home, record['delivery_id'],
|
||||
record.get('retry_admission_id') or record['admission_id'])
|
||||
live, interim = peer_wait_admission(authority, record)
|
||||
if live is not None and not interim:
|
||||
_watch_reply(authority, home, record['delivery_id'], live)
|
||||
else:
|
||||
await _maybe_retry(authority, home, path, record)
|
||||
row = authority.db.get_session_by_title('Bot Chat')
|
||||
@@ -444,6 +455,7 @@ async def _admit(authority, actor, home, root, key, message, ref, live, entry, a
|
||||
_write(path, record)
|
||||
receipt = await authority.admit_automation(authority.runner._adapter_for_source(live.source), event, 'bot:' + key)
|
||||
record.update(status='canonical', admission_id=receipt.admission_id)
|
||||
record.update(_result(authority, record)) # publish the outcome senders poll, not a bare marker
|
||||
_write(path, record)
|
||||
if receipt.status in {'queued', 'started'}:
|
||||
_watch_reply(authority, home, key, receipt.admission_id)
|
||||
|
||||
@@ -182,3 +182,45 @@ async def test_peer_dm_waiter_follows_the_retry_admission_to_its_answer(bot):
|
||||
finite.execute_finite_admission = execute
|
||||
assert (receipt['status'], receipt['reply']) == ('settled', 'pong'), receipt
|
||||
assert receipt['retry_admission_id']
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_receipt_file_stays_pending_while_a_draining_owner_leaves_the_retry_to_its_successor(bot):
|
||||
"""Senders wait on the published receipt file, not an authority RPC. An original that failed
|
||||
transiently while the owner drains is interim there (``claimed``), never the final ``failed``:
|
||||
the restarted owner's recovery admits the one retry and the same wait gets its answer."""
|
||||
from gateway.session_bot import deliver, recover_bot_deliveries
|
||||
from tools.bot_live_delivery import await_delivery_async
|
||||
import gateway.session_finite as finite
|
||||
started, gate = asyncio.Event(), asyncio.Event()
|
||||
execute = finite.execute_finite_admission
|
||||
|
||||
async def held(authority, ref, row):
|
||||
if not row['request_id'].endswith(':retry'):
|
||||
started.set()
|
||||
await gate.wait()
|
||||
return await execute(authority, ref, row)
|
||||
|
||||
finite.execute_finite_admission = held
|
||||
try:
|
||||
bot.errors[:] = ['Error code: 429 - rate limit exceeded']
|
||||
await deliver(bot.connection, dict(id=KEY, profile='default', message='ping'))
|
||||
await asyncio.wait_for(started.wait(), 5)
|
||||
bot.authority.runner._draining = True # shutdown starts while the original runs
|
||||
gate.set()
|
||||
for _ in range(200):
|
||||
await asyncio.sleep(0.02)
|
||||
if _admissions(bot)[0]['status'] == 'terminal':
|
||||
break
|
||||
await asyncio.sleep(0.1)
|
||||
interim = await await_delivery_async(bot.home, KEY, 0.2)
|
||||
assert interim['status'] == 'claimed' and len(_admissions(bot)) == 1, interim
|
||||
waiting = asyncio.create_task(await_delivery_async(bot.home, KEY, 10))
|
||||
bot.authority.runner._draining = False # the successor owner's startup recovery
|
||||
await recover_bot_deliveries(bot.authority)
|
||||
receipt = await asyncio.wait_for(waiting, 10)
|
||||
finally:
|
||||
finite.execute_finite_admission = execute
|
||||
assert (receipt['status'], receipt['reply']) == ('settled', 'pong'), receipt
|
||||
assert [r['request_id'] for r in _admissions(bot)] == ['bot:' + KEY, 'bot:' + KEY + ':retry']
|
||||
|
||||
|
||||
@@ -238,3 +238,34 @@ def test_non_dict_ticket_fails_exact_id_reads_closed(tmp_path):
|
||||
with pytest.raises(ValueError):
|
||||
mailbox.read_delivery_result(tmp_path, "e" * 32)
|
||||
assert bad.read_text(encoding="utf-8") == '"oops"'
|
||||
|
||||
|
||||
def test_receipt_wait_polls_the_local_receipt_and_outlives_an_unreachable_owner(tmp_path, monkeypatch):
|
||||
"""A sender's wait reads the receipt file the owner republishes; it never dials the authority
|
||||
(one fresh websocket per 0.5 s tick for up to 30 min) and an owner restart mid-wait is just a
|
||||
longer pending stretch, not an exception that abandons the reply."""
|
||||
import threading
|
||||
|
||||
dials = []
|
||||
|
||||
def unreachable(home, params):
|
||||
dials.append(params["id"])
|
||||
raise ValueError("profile authority is not ready")
|
||||
|
||||
monkeypatch.setattr(mailbox, "authority_delivery", unreachable)
|
||||
monkeypatch.setattr(mailbox, "_POLL_SECONDS", 0.01)
|
||||
key = "f" * 32
|
||||
admitted = dict(delivery_id=key, profile_home=str(tmp_path.resolve()), session_id="bot", principal_id="owner",
|
||||
message="hello", admission_id="adm-1", status="canonical")
|
||||
with mailbox._locked(tmp_path) as root:
|
||||
mailbox._write(root / f"{key}.json", admitted)
|
||||
pending = mailbox.await_delivery(tmp_path, key, 0.05)
|
||||
assert pending["status"] == "queued", pending # admitted, outcome not yet published
|
||||
|
||||
def publish():
|
||||
with mailbox._locked(tmp_path) as root:
|
||||
mailbox._write(root / f"{key}.json", dict(admitted, status="settled", reply="PONG"))
|
||||
threading.Timer(0.1, publish).start()
|
||||
settled = mailbox.await_delivery(tmp_path, key, 5)
|
||||
assert (settled["status"], settled["reply"]) == ("settled", "PONG")
|
||||
assert dials == []
|
||||
|
||||
@@ -260,6 +260,15 @@ class _FakeAuthority:
|
||||
raise ValueError("admission_conflict")
|
||||
return {k: record[k] for k in ("status", "delivery_id", "profile_home", "session_id", "reply")}
|
||||
|
||||
def settle(self, delivery_id, **outcome):
|
||||
"""The owner settles the admission and republishes its receipt file (what waiters poll)."""
|
||||
from tools import bot_live_delivery as live
|
||||
|
||||
record = self.records[delivery_id]
|
||||
record.update(outcome)
|
||||
with live._locked(record["profile_home"]) as root:
|
||||
live._write(root / f"{delivery_id}.json", record)
|
||||
|
||||
|
||||
def _canonical_target(monkeypatch, *targets: Path) -> _FakeAuthority:
|
||||
"""Every ``targets`` profile home has a ready authority (its Bot Chat is admitted canonically);
|
||||
@@ -724,7 +733,7 @@ def test_live_dm_runner_retry_never_reexecutes_failed_admission(tmp_path, monkey
|
||||
assert queued["status"] == "queued"
|
||||
# The authority settles the admission as failed; a retry of the same runner
|
||||
# reads that exact receipt (same id) and never admits or executes again.
|
||||
authority.records[queued["delivery_id"]]["status"] = "failed"
|
||||
authority.settle(queued["delivery_id"], status="failed")
|
||||
from tools import bot_live_delivery as live
|
||||
monkeypatch.setattr(live, "find_canonical_live_owner", lambda h: pytest.fail("intent is pinned"))
|
||||
assert bot_mode_dm._run_delivery(argv, str(dm_file), stdin_file=False) == 1
|
||||
@@ -750,8 +759,7 @@ def _admitted_live_dm(tmp_path, monkeypatch, delivery_id):
|
||||
def test_live_dm_wait_reports_reply_after_initial_wait_budget(tmp_path, monkeypatch, capsys):
|
||||
"""A retained admission still delivers its reply after the first wait window (main a94b9758313)."""
|
||||
live, authority, record = _admitted_live_dm(tmp_path, monkeypatch, "a" * 32)
|
||||
settling = threading.Timer(0.05, lambda: authority.records[record["delivery_id"]].update(
|
||||
status="settled", reply="PONG"))
|
||||
settling = threading.Timer(0.05, lambda: authority.settle(record["delivery_id"], status="settled", reply="PONG"))
|
||||
settling.start()
|
||||
try:
|
||||
exit_code = bot_mode_dm._wait_live_dm(str(tmp_path), record["delivery_id"])
|
||||
@@ -1172,7 +1180,7 @@ def test_settled_live_wait_unlinks_the_intent_but_a_pending_one_keeps_it(tmp_pat
|
||||
waiting.start()
|
||||
time.sleep(0.05)
|
||||
pending_kept = waiting.is_alive() and intent.exists() and dm_file.exists()
|
||||
authority.records[record["delivery_id"]].update(status="settled", reply="ok")
|
||||
authority.settle(record["delivery_id"], status="settled", reply="ok")
|
||||
waiting.join(timeout=2)
|
||||
|
||||
assert pending_kept, "a pending delivery keeps its intent while the runner waits"
|
||||
|
||||
@@ -332,6 +332,17 @@ _PENDING = ("queued", "claimed")
|
||||
_POLL_SECONDS = 0.5
|
||||
|
||||
|
||||
def _poll_receipt(profile_home: Path | str, delivery_id: str) -> dict[str, Any] | None:
|
||||
"""A waiter's read: the receipt file the owner republishes when the admission settles (and on
|
||||
restart recovery). Never an authority RPC: a wait outlives owner restarts, and replaying the
|
||||
envelope (``read_delivery_result``) is for producers re-confirming their admission."""
|
||||
record = _read(_root(profile_home) / f"{_delivery_id(delivery_id)}.json")
|
||||
if record is not None and record.get("status") == "canonical":
|
||||
# Admitted with its outcome not yet published (an older owner's last write): pending.
|
||||
return {**record, "status": "queued"}
|
||||
return record
|
||||
|
||||
|
||||
def await_delivery(
|
||||
profile_home: Path | str, delivery_id: str, timeout: float | None,
|
||||
*, should_stop: Callable[[], bool] | None = None,
|
||||
@@ -342,11 +353,12 @@ def await_delivery(
|
||||
Desktop relay, ``hermes peer dm`` and ``hermes peer run``) waits on the same receipt; keeping
|
||||
the loop here is what stops the lanes drifting (one lane returned a receipt sentence instead
|
||||
of the reply, two never waited at all). Returns the last record read — still pending when the
|
||||
budget lapsed, None when the receipt was never readable.
|
||||
budget lapsed, None when the receipt was never readable. Polls the local receipt file only, so
|
||||
an owner restart mid-wait is just a longer pending stretch.
|
||||
"""
|
||||
deadline = None if timeout is None else time.monotonic() + timeout
|
||||
while True:
|
||||
record = read_delivery_result(profile_home, delivery_id)
|
||||
record = _poll_receipt(profile_home, delivery_id)
|
||||
if record is None or record["status"] not in _PENDING:
|
||||
return record
|
||||
if should_stop is not None and should_stop():
|
||||
@@ -366,7 +378,7 @@ async def await_delivery_async(
|
||||
|
||||
deadline = None if timeout is None else time.monotonic() + timeout
|
||||
while True:
|
||||
record = await asyncio.to_thread(read_delivery_result, profile_home, delivery_id)
|
||||
record = await asyncio.to_thread(_poll_receipt, profile_home, delivery_id)
|
||||
if record is None or record["status"] not in _PENDING:
|
||||
return record
|
||||
if should_stop is not None and should_stop():
|
||||
|
||||
Reference in New Issue
Block a user