The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): keep a reconnect-only rejection for the adapter when standalone fails
Jay Zhou63d8a0d5b20e
diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.pyindex 5925689f6e7..807f728ae8a 100644--- a/cron/scheduler_delivery.py+++ b/cron/scheduler_delivery.py@@ -1324,6 +1324,7 @@ class _TargetDelivery:inchannel_continuable: boolopened_thread_id: Optional[str]live_adapter_ready: bool = False+ live_error: Optional[str] = None # the live lane's own rejection string, e.g. "send_path_degraded"@propertydef is_relay(self) -> bool:@@ -1331,7 +1332,9 @@ class _TargetDelivery:@propertydef where(self) -> str:- return f"{self.platform_name}:{self.chat_id}"+ # A topic-routed target without its thread id names the wrong lane in failure reports.+ base = f"{self.platform_name}:{self.chat_id}"+ return f"{base}:{self.thread_id}" if self.thread_id else basedef _note_target_error(job: dict, msg: str, errors: list) -> None:@@ -1532,6 +1535,7 @@ def _live_send_text(else:err, shape = getattr(send_result, "error", None), type(send_result).__name__msg = f"live adapter send to {t.where} returned unconfirmed result ({shape}, error={err})"+ t.live_error = str(err) if err else None_warn_live_lane_failure(job, msg, t.is_relay)target_errors.append(msg)return False, False, None@@ -1747,6 +1751,35 @@ def _standalone_send(return _failed(e)+def _queue_for_live_reconnect(t: _TargetDelivery, content: str, media_files: list, delivery_errors: list) -> None:+ """Hand a payload the live lane rejected as reconnect-only (``send_path_degraded``) and the+ standalone lane then failed to send to the delivery ledger, as a failed reconnect-only row+ owned by the adapter that rejected it: the post-reconnect sweep redelivers it (#125363). Only+ reached after standalone failed, so nothing was sent and a replay cannot duplicate. The ledger+ carries text only; dropped attachments are reported."""+ try:+ from gateway.delivery_ledger import (+ compute_obligation_id, is_reconnect_only, ledger_enabled, mark_failed, record_obligation)+ if not is_reconnect_only(t.live_error) or not ledger_enabled():+ return+ session_key = f"cron:{t.platform_name}:{t.chat_id}" + (f":{t.thread_id}" if t.thread_id else "")+ obligation_id = compute_obligation_id(session_key, f"job:{t.job.get('id', '?')}", content)+ record_obligation(+ obligation_id=obligation_id, session_key=session_key, platform=t.platform_name,+ chat_id=str(t.chat_id), thread_id=t.thread_id, content=content,+ adapter_profile=getattr(getattr(t.transport, "adapter", None), "_owner_profile", None))+ mark_failed(obligation_id, str(t.live_error))+ except Exception:+ logger.warning("Job '%s': could not queue %s for post-reconnect redelivery",+ t.job.get("id"), t.where, exc_info=True)+ return+ note = f"queued text for {t.where} for redelivery once the live adapter reconnects"+ if media_files:+ note += f" ({len(media_files)} attachment(s) not queued)"+ logger.warning("Job '%s': %s", t.job.get("id"), note)+ delivery_errors.append(note)++def _deliver_standalone(t: _TargetDelivery, content: str, media_files: list, target_errors: list, delivery_errors: list,) -> None:@@ -1766,6 +1799,9 @@ def _deliver_standalone(if err is not None:target_errors.append(err)delivery_errors.extend(target_errors)+ # A satellite profile's worker has no platform token, so standalone cannot stand in for a+ # live adapter that is only waiting to reconnect: keep the payload for that adapter.+ _queue_for_live_reconnect(t, content, media_files, delivery_errors)return# Standalone senders report per-file attachment failures in ``warnings`` while returning# success; surface them so a vanished attachment doesn't mark the run ok.diff --git a/tests/cron/test_cron_reconnect_only_rejection.py b/tests/cron/test_cron_reconnect_only_rejection.pynew file mode 100644index 00000000000..0698c760e0f--- /dev/null+++ b/tests/cron/test_cron_reconnect_only_rejection.py@@ -0,0 +1,77 @@+"""A cron payload the live lane rejected as reconnect-only is not lost when standalone fails (#125363).++``send_path_degraded`` means the adapter that owns the connection will deliver after it reconnects.+A satellite profile's cron worker has no platform token, so the standalone fallback fails; the payload+must then wait in the delivery ledger for that adapter's post-reconnect sweep. A profile whose+standalone send works keeps delivering immediately, attachments included.+"""++import pytest++import cron.scheduler_delivery as sd+from gateway import delivery_ledger as dl++[email protected](autouse=True)+def _fresh_ledger(tmp_path, monkeypatch):+ home = tmp_path / "hermes"+ home.mkdir()+ monkeypatch.setattr(dl, "_db_path", lambda: home / "state.db")+ monkeypatch.setattr(dl, "ledger_enabled", lambda config=None: True)+ monkeypatch.setattr(sd, "_maybe_mirror_cron_delivery", lambda *a, **k: None)+++def _target(*, live_error="send_path_degraded", relay=False, thread_id="42", profile="satellite"):+ adapter = type("Adapter", (), {"_owner_profile": profile})()+ transport = type("Transport", (), {"adapter": adapter, "is_relay": relay})()+ fields = {name: None for name in sd._TargetDelivery.__dataclass_fields__}+ fields.update(job={"id": "job-1"}, platform_name="telegram", chat_id="-100", thread_id=thread_id,+ transport=transport, mirror_text="", origin={}, live_error=live_error)+ return sd._TargetDelivery(**fields)+++def _standalone(monkeypatch, result, err):+ sent = []+ monkeypatch.setattr(sd, "_standalone_send", lambda t, content, media: sent.append(media) or (result, err))+ return sent+++def _deliver(t, media=()):+ target_errors, delivery_errors = [], []+ sd._deliver_standalone(t, "the report", list(media), target_errors, delivery_errors)+ return delivery_errors+++def test_failed_standalone_queues_the_payload_for_the_reconnect_sweep(monkeypatch):+ _standalone(monkeypatch, None, "You must pass the token from BotFather")+ errors = _deliver(_target())+ assert any("queued text for telegram:-100:42" in e for e in errors)+ claimed = dl.sweep_failed_for_runtime("telegram", profile="satellite")+ assert [(row["chat_id"], row["thread_id"], row["content"]) for row in claimed] == [("-100", "42", "the report")]+++def test_working_standalone_still_delivers_now_and_queues_nothing(monkeypatch):+ sent = _standalone(monkeypatch, {"success": True}, None)+ assert _deliver(_target(), media=["chart.png"]) == []+ assert sent == [["chart.png"]]+ assert dl.sweep_failed_for_runtime("telegram", profile="satellite") == []++[email protected]("target", [_target(live_error="chat not found"), _target(live_error=None),+ _target(relay=True)])+def test_other_failures_are_not_queued(monkeypatch, target):+ _standalone(monkeypatch, None, "boom")+ errors = _deliver(target)+ assert not any("queued" in e for e in errors)+ assert dl.sweep_failed_for_runtime("telegram", profile="satellite") == []+++def test_dropped_attachments_are_reported(monkeypatch):+ _standalone(monkeypatch, None, "You must pass the token from BotFather")+ errors = _deliver(_target(), media=["a.png", "b.pdf"])+ assert any("2 attachment(s) not queued" in e for e in errors)+++def test_failure_reports_name_the_thread():+ assert _target(thread_id="42").where == "telegram:-100:42"+ assert _target(thread_id=None).where == "telegram:-100"