The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot-mode): a schema-damaged mailbox ticket no longer wedges Bot Chat delivery
teknium197942a29bb71
diff --git a/tests/tools/test_bot_live_owner_delivery.py b/tests/tools/test_bot_live_owner_delivery.pyindex 4402ab55ad7..3c07f6d0656 100644--- a/tests/tools/test_bot_live_owner_delivery.py+++ b/tests/tools/test_bot_live_owner_delivery.py@@ -183,3 +183,56 @@ def test_non_dict_ticket_is_skipped_by_scans_and_fails_exact_id_reads_closed(tmpwith pytest.raises(ValueError):mailbox.read_delivery_result(tmp_path, "e" * 32)assert bad.read_text(encoding="utf-8") == '"oops"'+++def test_schema_damaged_ticket_does_not_wedge_bulk_scans(tmp_path, caplog):+ """Valid JSON that lost a field must degrade like corrupt JSON: skipped, warned once, never raised."""+ 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, "healthy", delivery_id="d" * 32)+ root = tmp_path / "runtime" / mailbox.DELIVERY_DIR_NAME+ damaged = {+ root / f"{'a' * 32}.json": "{}",+ root / f"{'b' * 32}.json": json.dumps(dict(+ delivery_id="b" * 32, id="b" * 32, status="queued", created_at=1,+ sequence=1, owner=None, message="owner lost")),+ root / f"{'c' * 32}.json": json.dumps(dict(+ delivery_id="c" * 32, id="c" * 32, status="queued", created_at=2,+ sequence="old", owner=owner, message="sequence lost", **owner)),+ root / f"{'e' * 32}.json": json.dumps(dict(+ delivery_id="../wrong", id="../wrong", status="queued", created_at=3,+ sequence=3, owner=owner, message="id lost", **owner)),+ root / f"{'1' * 32}.json": json.dumps(dict(+ delivery_id="1" * 32, id="1" * 32, status=[], created_at=4,+ sequence=4, owner=owner, message="status lost", **owner)),+ }+ for path, contents in damaged.items():+ path.write_text(contents, encoding="utf-8")+ with caplog.at_level(logging.WARNING, logger="tools.bot_live_delivery"):+ admitted = mailbox.deliver_to_live_owner(tmp_path, owner, "also healthy", delivery_id="f" * 32)+ 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"]+ for _ in range(3):+ assert mailbox.claim_pending_delivery(tmp_path, owner) is None+ assert admitted["sequence"] == queued["sequence"] + 1+ assert {path: path.read_text(encoding="utf-8") for path in damaged} == damaged+ skipped = [r.message for r in caplog.records if r.message.startswith("bot_live_delivery: skipping unreadable ticket")]+ assert len(skipped) == len(damaged), "each damaged ticket warns once per process, not per scan"+++def test_existing_mailbox_lock_does_not_fsync_parent_dirs(tmp_path, monkeypatch):+ """The idle poller re-enters the lock twice a second; only a freshly created mailbox links its parents."""+ from tools import bot_live_delivery as mailbox++ calls = []+ monkeypatch.setattr(mailbox, "fsync_directory", lambda path: calls.append(path))+ with mailbox._locked(tmp_path):+ pass+ assert len(calls) == 2+ with mailbox._locked(tmp_path):+ pass+ assert len(calls) == 2diff --git a/tests/tui_gateway/test_bot_live_owner_delivery.py b/tests/tui_gateway/test_bot_live_owner_delivery.pyindex 2e6263ad16e..e15a72ecb2e 100644--- a/tests/tui_gateway/test_bot_live_owner_delivery.py+++ b/tests/tui_gateway/test_bot_live_owner_delivery.py@@ -148,3 +148,28 @@ def test_failing_mailbox_poll_warns_once_per_window():"Bot live-owner delivery poll failed (0 repeat(s) suppressed since the last report)","Bot live-owner delivery poll failed (2 repeat(s) suppressed since the last report)"]assert all(r.exc_info for r in warnings)+++def test_mailbox_poll_delivers_past_a_schema_damaged_ticket(monkeypatch, tmp_path):+ """A `{}` ticket beside a healthy envelope must not wedge the live poller's claim (real mailbox on disk)."""+ import tools.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, "healthy", delivery_id="d" * 32)+ (mailbox._root(tmp_path) / f"{'a' * 32}.json").write_text("{}", encoding="utf-8")+ monkeypatch.setattr(mailbox, "find_canonical_live_owner", lambda home: owner)+ submitted = []+ def submit(rid, sid, session, text, **kwargs):+ submitted.append(text)+ kwargs["terminal_callback"]({"status": "settled", "text": "reply"})+ return True+ poll = rebind(session_notifications._poll_bot_live_delivery_once, {+ "_session_home": lambda session: tmp_path,+ "_session_turn_admission": _session_turn_admission,+ "_run_prompt_submit": submit,+ "_notif_release_turn": lambda session: session.update(running=False),+ })+ session = {"history_lock": threading.RLock(), "agent": object(), "session_key": "chat",+ "active_session_lease": SimpleNamespace(lease_id="lease", released=False)}+ assert poll("live", session) is True+ assert submitted == ["healthy"]+ assert mailbox.read_delivery_result(tmp_path, queued["delivery_id"])["status"] == "settled"diff --git a/tools/bot_live_delivery.py b/tools/bot_live_delivery.pyindex 1668f2925d6..6830dc6b0ca 100644--- a/tools/bot_live_delivery.py+++ b/tools/bot_live_delivery.py@@ -90,11 +90,16 @@ def has_mailbox(profile_home: Path | str) -> bool:@contextmanagerdef _locked(home: Path | str):root = _root(home)+ created = not root.is_dir()root.parent.mkdir(parents=True, exist_ok=True)root.mkdir(mode=0o700, exist_ok=True)root.chmod(0o700)- fsync_directory(root.parent)- fsync_directory(root.parent.parent)+ if created:+ # Only a fresh mailbox dir needs its parents durably linked; the live+ # poller re-enters this lock twice a second per profile, and two+ # directory fsyncs per idle poll was measurable disk churn for nothing.+ fsync_directory(root.parent)+ fsync_directory(root.parent.parent)lock = root / ".lock"fd = os.open(lock, os.O_CREAT | os.O_WRONLY, 0o600)os.close(fd)@@ -118,8 +123,30 @@ def _read(path: Path) -> dict[str, Any] | None:_warned_unreadable: set[Path] = set()+def _ticket_shape_error(path: Path, record: dict[str, Any]) -> str | None:+ """Why a parsed ticket is unusable by the scans, or None when it is well-formed.++ A ticket that parses as JSON but lost a field (truncated rewrite, foreign+ writer, hand edit) used to raise KeyError/TypeError out of the sequence+ scan and the claim sweep — wedging admission and delivery for the whole+ profile exactly like corrupt JSON did before ``_scan_read`` existed.+ """+ owner = record.get("owner")+ created_at, sequence = record.get("created_at"), record.get("sequence", record.get("created_at"))+ if record.get("delivery_id") != path.stem or record.get("id") != path.stem:+ return "id does not match filename"+ status = record.get("status")+ if not isinstance(status, str) or status not in ({"queued", "claimed"} | _TERMINAL):+ return f"unknown status {status!r}"+ if not all(isinstance(v, int) and not isinstance(v, bool) for v in (created_at, sequence)):+ return "created_at/sequence are not integers"+ if not isinstance(owner, dict) or not all(isinstance(owner.get(k), str) and owner[k] for k in _OWNER_KEYS):+ return "owner pin is incomplete"+ return None++def _scan_read(path: Path) -> dict[str, Any] | None:- """Bulk-scan variant: one unreadable ticket must not wedge the whole dir.+ """Bulk-scan variant: one unreadable or malformed ticket must not wedge the whole dir.Directory scans (sequence high-water mark, queued-claim sweep) may onlytreat a file as absent when it is provably absent; an unreadable ticket@@ -130,10 +157,13 @@ def _scan_read(path: Path) -> dict[str, Any] | None:"""try:record = _read(path)+ problem = None if record is None else _ticket_shape_error(path, record)except (OSError, ValueError) as exc: # ValueError: corrupt JSON and invalid UTF-8 alike+ record, problem = None, str(exc)+ if problem is not None:level = logging.DEBUG if path in _warned_unreadable else logging.WARNING_warned_unreadable.add(path)- log.log(level, "bot_live_delivery: skipping unreadable ticket %s (%s)", path.name, exc)+ log.log(level, "bot_live_delivery: skipping unreadable ticket %s (%s)", path.name, problem)return None_warned_unreadable.discard(path)return record