fix: retire the legacy Bot mailbox producer and inference drain
This commit is contained in:
19
tests/tools/test_bot_legacy_producer.py
Normal file
19
tests/tools/test_bot_legacy_producer.py
Normal file
@@ -0,0 +1,19 @@
|
||||
"""A stale owner advertisement must never create another execution queue."""
|
||||
import pytest
|
||||
from tools.bot_live_delivery import deliver_to_live_owner
|
||||
|
||||
|
||||
def test_legacy_owner_requires_a_live_authority_before_admission(tmp_path):
|
||||
owner = dict(profile_home=str(tmp_path), session_id='legacy', lease_id='dead', live_session_id='old-ui')
|
||||
with pytest.raises(ValueError, match='authority'):
|
||||
deliver_to_live_owner(tmp_path, owner, 'message', delivery_id='e' * 32)
|
||||
assert not (tmp_path / 'runtime' / 'bot_live_delivery' / ('e' * 32 + '.json')).exists()
|
||||
|
||||
|
||||
def test_legacy_poller_cannot_claim_an_unmigrated_input(tmp_path):
|
||||
from tools.bot_live_delivery import _locked, _write, claim_pending_delivery
|
||||
owner = dict(profile_home=str(tmp_path), session_id='legacy', lease_id='dead', live_session_id='old-ui')
|
||||
with _locked(tmp_path) as root:
|
||||
_write(root / ('f' * 32 + '.json'), dict(owner=owner, delivery_id='f' * 32,
|
||||
message='old queued input', status='queued', created_at=1))
|
||||
assert claim_pending_delivery(tmp_path, owner) is None
|
||||
@@ -7,7 +7,7 @@ def test_local_dm_cannot_fall_back_to_a_cli_turn(tmp_path, monkeypatch, capsys):
|
||||
payload = tmp_path / 'dm.txt'
|
||||
payload.write_text('private DM')
|
||||
calls = []
|
||||
monkeypatch.setattr(dm, '_run_local_turn', lambda *args: calls.append(args) or 0)
|
||||
monkeypatch.setattr(dm, '_run_local_turn', lambda *args: calls.append(args) or 0, raising=False)
|
||||
monkeypatch.setattr(dm, '_local_delivery_home', lambda argv: None)
|
||||
assert dm._run_delivery(['hermes', '-p', 'missing'], str(payload), stdin_file=False) == 1
|
||||
assert calls == []
|
||||
|
||||
@@ -148,73 +148,19 @@ def deliver_to_live_owner(
|
||||
state. Reusing an id with a different payload is an error, never an overwrite.
|
||||
"""
|
||||
pinned = _owner(profile_home, owner)
|
||||
if owner.get("canonical"):
|
||||
home = Path(profile_home).resolve()
|
||||
return authority_delivery(home, dict(id=_delivery_id(delivery_id or uuid.uuid4().hex),
|
||||
profile=home.name if home.parent.name == "profiles" else "default",
|
||||
message=message, session_id=pinned["session_id"]))
|
||||
if not isinstance(message, str):
|
||||
raise ValueError("message must be a string")
|
||||
key = _delivery_id(delivery_id if delivery_id is not None else uuid.uuid4().hex)
|
||||
with _locked(profile_home) as root:
|
||||
path = root / f"{key}.json"
|
||||
existing = _read(path)
|
||||
if existing is not None:
|
||||
if existing["owner"] != pinned or existing["message"] != message:
|
||||
raise ValueError("delivery id already belongs to a different payload")
|
||||
return existing
|
||||
# Wall time can roll back. Permanent receipts retain the admission
|
||||
# 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
|
||||
record = dict(delivery_id=key, id=key, owner=pinned, **pinned,
|
||||
message=message, status="queued", created_at=time.time_ns(),
|
||||
sequence=sequence)
|
||||
_write(path, record)
|
||||
return record
|
||||
home = Path(profile_home).resolve()
|
||||
return authority_delivery(home, dict(id=_delivery_id(delivery_id or uuid.uuid4().hex),
|
||||
profile=home.name if home.parent.name == "profiles" else "default",
|
||||
message=message, session_id=pinned["session_id"]))
|
||||
|
||||
|
||||
def _matches(home: Path | str, record: dict, owner: dict) -> bool:
|
||||
pinned = record["owner"]
|
||||
if any(pinned[key] != owner[key] for key in ("profile_home", "lease_id", "live_session_id")):
|
||||
return False
|
||||
if pinned["session_id"] == owner["session_id"]:
|
||||
return True
|
||||
from hermes_state import SessionDB
|
||||
def claim_pending_delivery(profile_home, owner):
|
||||
"""Retired UI poller: only session_bot may migrate and admit queued records.
|
||||
|
||||
db = SessionDB(db_path=Path(home) / "state.db", read_only=True)
|
||||
try:
|
||||
return db.get_compression_tip(pinned["session_id"]) == owner["session_id"]
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def claim_pending_delivery(
|
||||
profile_home: Path | str, owner: dict[str, Any],
|
||||
) -> dict[str, Any] | None:
|
||||
"""Claim oldest matching input exactly once; caller supplies its current lease.
|
||||
|
||||
A lease transfer across compression is accepted only along the original
|
||||
stored session's compression chain. A new lease/live session cannot steal it.
|
||||
Caller must hold its normal turn-admission guard before invoking this.
|
||||
Keep this refusal until the legacy notification poller's call site is removed.
|
||||
A previously claimed record can still publish its terminal receipt below.
|
||||
"""
|
||||
current = _owner(profile_home, owner)
|
||||
if not _root(profile_home).is_dir():
|
||||
return None
|
||||
with _locked(profile_home) as root:
|
||||
pending = []
|
||||
for path in root.glob("*.json"):
|
||||
record = _read(path)
|
||||
if record is not None and record["status"] == "queued" and _matches(profile_home, record, current):
|
||||
pending.append(record)
|
||||
if not pending:
|
||||
return None
|
||||
record = min(pending, key=lambda item: (
|
||||
item.get("sequence", item["created_at"]), item["delivery_id"]))
|
||||
record.update(status="claimed", claimed_at=time.time_ns())
|
||||
_write(root / f"{record['delivery_id']}.json", record)
|
||||
return record
|
||||
return None
|
||||
|
||||
|
||||
def complete_delivery(
|
||||
|
||||
@@ -355,50 +355,6 @@ def _delivery_lock(argv: list[str], *, stdin_file: bool):
|
||||
return acquire_turn_lock(_hermes_root(Path(_default_home())), argv[2])
|
||||
|
||||
|
||||
def _run_local_turn(argv: list[str], dm_file: str) -> int:
|
||||
"""One Bot Chat turn via ``--query-file`` (plus one policy-gated retry); re-emits
|
||||
the transport's streams and returns its exit code. Transient failures re-run the
|
||||
same session; a context_overflow re-run lets the retried turn's pre-API compaction
|
||||
compact the transcript first (no fresh session is ever minted). Auth/quota/config never retry."""
|
||||
|
||||
def _turn():
|
||||
return subprocess.run([*argv, "--query-file", dm_file], check=False, stdin=subprocess.DEVNULL,
|
||||
capture_output=True, text=True)
|
||||
|
||||
proc = _turn()
|
||||
if proc.returncode != 0:
|
||||
from tools.bot_failure_reasons import RETRY_NONE, classify_agent_error, retry_action
|
||||
|
||||
if retry_action(classify_agent_error((proc.stderr or proc.stdout or "").strip()[-500:])) != RETRY_NONE:
|
||||
proc = _turn()
|
||||
stderr_text = proc.stderr or ""
|
||||
reason = next((line.removeprefix("hermes-refusal-reason: ").strip()
|
||||
for line in stderr_text.splitlines()
|
||||
if line.startswith("hermes-refusal-reason: ")), None)
|
||||
# A code wins over prose, including unknown codes from newer CLIs.
|
||||
# Only older CLIs without a marker need the historical wording fallback.
|
||||
refused_not_owned = (reason == "SESSION_NOT_OWNED" if reason is not None
|
||||
else "already has a live owner" in stderr_text)
|
||||
if proc.returncode != 0 and refused_not_owned:
|
||||
# The target's Bot Chat is held live by another surface (Desktop); the turn
|
||||
# never ran — tell the sender plainly instead of leaking a raw lease error.
|
||||
# See #100523.
|
||||
who = argv[argv.index("-p") + 1] if "-p" in argv[:-1] else "the teammate"
|
||||
print(json.dumps({
|
||||
"error": f"Delivery failed: @{who}'s Bot Chat is open on another "
|
||||
"surface right now, so your message was NOT delivered. Try again later.",
|
||||
"reason": "target_busy",
|
||||
}))
|
||||
return 1
|
||||
# Re-emit the transport's streams: stdout is the reply text the
|
||||
# completion notification carries back to the sending agent.
|
||||
for stream, text in ((sys.stdout, proc.stdout), (sys.stderr, proc.stderr)):
|
||||
if text:
|
||||
stream.write(text)
|
||||
stream.flush()
|
||||
return proc.returncode
|
||||
|
||||
|
||||
def _admit_live_dm(profile_home: Path | None, dm_file: str) -> dict | None:
|
||||
"""Pin intent before admission; retries may inspect, never change transport."""
|
||||
from tools.bot_live_delivery import (
|
||||
|
||||
Reference in New Issue
Block a user