The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tools): stop one unreadable ticket from wedging bot live delivery
liuhao102468865580adf2
diff --git a/tests/tools/test_bot_live_owner_delivery.py b/tests/tools/test_bot_live_owner_delivery.pyindex c35d5d8fd29..21f268c5ecc 100644--- a/tests/tools/test_bot_live_owner_delivery.py+++ b/tests/tools/test_bot_live_owner_delivery.py@@ -106,3 +106,51 @@ def test_delivery_keeps_the_sender_and_refuses_a_different_one_under_the_same_idwith pytest.raises(ValueError):mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id="b" * 32, author={**author, "id": "bot:other"})assert "author" not in mailbox.deliver_to_live_owner(tmp_path, owner, "no sender", delivery_id="c" * 32)++[email protected](os.name == "nt" or getattr(os, "geteuid", lambda: 1)() == 0,+ reason="needs POSIX file permissions for an unreadable ticket")+def test_unreadable_ticket_does_not_wedge_bulk_scans(tmp_path, caplog):+ import logging++ from tools import bot_live_delivery as mailbox++ owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat",+ lease_id="lease", live_session_id="live")+ queued = mailbox.deliver_to_live_owner(tmp_path, owner, "readable", delivery_id="d" * 32)+ root = tmp_path / "runtime" / mailbox.DELIVERY_DIR_NAME+ unreadable = root / f"{'e' * 32}.json"+ unreadable.write_text('{"status": "queued"}', encoding="utf-8")+ unreadable.chmod(0)+ corrupt = root / f"{'1' * 32}.json"+ corrupt.write_text("{not json", encoding="utf-8")+ with caplog.at_level(logging.WARNING, logger="tools.bot_live_delivery"):+ # Sender side: admission of a fresh id must survive the sequence sweep.+ admitted = mailbox.deliver_to_live_owner(tmp_path, owner, "second", delivery_id="f" * 32)+ # Receiver side: every readable queued ticket must still be claimed, in order.+ assert mailbox.claim_pending_delivery(tmp_path, owner)["delivery_id"] == queued["delivery_id"]+ assert mailbox.claim_pending_delivery(tmp_path, owner)["delivery_id"] == admitted["delivery_id"]+ assert mailbox.claim_pending_delivery(tmp_path, owner) is None+ assert admitted["status"] == "queued"+ assert any(record.message.startswith(f"bot_live_delivery: skipping unreadable ticket {'e' * 32}.json")+ and "Permission denied" in record.message+ for record in caplog.records)++[email protected](os.name == "nt" or getattr(os, "geteuid", lambda: 1)() == 0,+ reason="needs POSIX file permissions for an unreadable ticket")+def test_unreadable_ticket_keeps_exact_id_reads_fail_closed(tmp_path):+ from tools import bot_live_delivery as mailbox++ owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat",+ lease_id="lease", live_session_id="live")+ unreadable = tmp_path / "runtime" / mailbox.DELIVERY_DIR_NAME / f"{'e' * 32}.json"+ unreadable.parent.mkdir(parents=True, exist_ok=True)+ unreadable.write_text('{"status": "queued"}', encoding="utf-8")+ unreadable.chmod(0)+ # Uninspectable is not absent: an exact-id retry must fail closed instead of+ # minting a fresh receipt that overwrites the possibly-live one (#109820).+ with pytest.raises(PermissionError):+ mailbox.deliver_to_live_owner(tmp_path, owner, "same id", delivery_id="e" * 32)+ with pytest.raises(PermissionError):+ mailbox.read_delivery_result(tmp_path, "e" * 32)diff --git a/tools/bot_live_delivery.py b/tools/bot_live_delivery.pyindex 1ede6188444..f31b244ddbd 100644--- a/tools/bot_live_delivery.py+++ b/tools/bot_live_delivery.py@@ -8,6 +8,7 @@ not permission to execute the same input again. Receipts are permanent.from __future__ import annotationsimport json+import loggingimport osimport reimport time@@ -20,6 +21,8 @@ from typing import Anyfrom hermes_cli.active_sessions import _FileLock+log = logging.getLogger(__name__)+DELIVERY_DIR_NAME = "bot_live_delivery"_OWNER_KEYS = ("profile_home", "session_id", "lease_id", "live_session_id")_TERMINAL = frozenset({"settled", "failed", "cancelled", "ambiguous"})@@ -105,6 +108,23 @@ def _read(path: Path) -> dict[str, Any] | None:return None+def _scan_read(path: Path) -> dict[str, Any] | None:+ """Bulk-scan variant: one unreadable ticket must not wedge the whole dir.++ Directory scans (sequence high-water mark, queued-claim sweep) may only+ treat a file as absent when it is provably absent; an unreadable ticket+ degrades to "that one delivery is uninspectable" with a loud warning.+ Exact-id reads (admission idempotency, completion, result lookup) keep+ using _read so a permission error still fails closed instead of+ licensing an overwrite of a possibly-live receipt.+ """+ try:+ return _read(path)+ except (OSError, json.JSONDecodeError) as exc:+ log.warning("bot_live_delivery: skipping unreadable ticket %s (%s)", path.name, exc)+ return None++def _write(path: Path, record: dict[str, Any]) -> None:atomic_json_write(path, record, indent=None, sort_keys=True, fsync_dir=True, mode=0o600)@@ -133,7 +153,7 @@ def deliver_to_live_owner(# high-water mark, allocated while holding the cross-process lock.sequence = max((record.get("sequence", record["created_at"])for candidate in root.glob("*.json")- if (record := _read(candidate)) is not None), default=0) + 1+ if (record := _scan_read(candidate)) is not None), default=0) + 1record = dict(delivery_id=key, id=key, owner=pinned, **pinned,message=message, status="queued", created_at=time.time_ns(),sequence=sequence, **({"author": dict(author)} if author else {}))@@ -171,7 +191,7 @@ def claim_pending_delivery(with _locked(profile_home) as root:pending = []for path in root.glob("*.json"):- record = _read(path)+ record = _scan_read(path)if record is not None and record["status"] == "queued" and _matches(profile_home, record, current):pending.append(record)if not pending: