Skip to content

The agent that grows with you

fix(cron): bound the standalone send lane with a wall-clock timeout

liuhao1024c53eaf0d827b
diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.py
index 54b9a728d93..5dea07c350b 100644
--- a/cron/scheduler_delivery.py
+++ b/cron/scheduler_delivery.py
@@ -702,6 +702,24 @@ def _get_bot_chat_delivery_timeout() -> int:
return 600
+def _get_standalone_send_timeout() -> int:
+ """Wall-clock bound for one standalone-lane send (#115469).
+
+ ``_send_to_platform``'s gateway-loop dispatch deliberately awaits its future with no
+ timeout ("the adapter and outer _run_async bound the wait") — but on this lane the
+ outer runner is a bare ``asyncio.run``, not ``model_tools._run_async``, so without a
+ bound here a reconnecting transport pins the run (and the restart drain behind it)
+ indefinitely. Mirrors the sibling lanes: live dispatch ``future.result(timeout=60)``,
+ thread fallback ``result(timeout=30)``. ``cron.standalone_send_timeout_seconds``;
+ default 60."""
+ try:
+ cfg = _sched.load_config()
+ value = int(cfg.get("cron", {}).get("standalone_send_timeout_seconds", 60))
+ return value if value > 0 else 60
+ except Exception:
+ return 60
+
+
_BOT_CHAT_STDERR_TAIL = 500
# stdout is the model's answer; only a short tail is persisted (jobs.json / ledger).
_BOT_CHAT_STDOUT_TAIL = 200
@@ -1674,8 +1692,16 @@ def _standalone_send(
if not content.strip() and not media_files:
return _warned(f"standalone send skipped (empty text and no media) for {t.where}")
coro = _send()
+ send_timeout = _get_standalone_send_timeout()
try:
- return asyncio.run(coro), None
+ return asyncio.run(asyncio.wait_for(coro, timeout=send_timeout)), None
+ except TimeoutError:
+ # The send may still complete on the gateway loop (the dispatch shield keeps an in-flight
+ # send un-cancelled); the run is released instead of waiting on it unbounded (#115469).
+ msg = (f"standalone send to {t.where} timed out after {send_timeout}s "
+ "(the send may still be in flight)")
+ logger.error("Job '%s': %s", job["id"], msg)
+ return None, msg
except RuntimeError as run_err:
# asyncio.run() refuses inside a running loop; close the unstarted coro, retry in a thread.
coro.close()
diff --git a/tests/cron/test_cron_live_delivery_confirmation.py b/tests/cron/test_cron_live_delivery_confirmation.py
index 6702bc7879a..b1f8964b351 100644
--- a/tests/cron/test_cron_live_delivery_confirmation.py
+++ b/tests/cron/test_cron_live_delivery_confirmation.py
@@ -18,6 +18,7 @@ and fail-closed on nothing-to-send.
import asyncio
import logging
+import time
from concurrent.futures import Future
from unittest.mock import MagicMock, patch
@@ -404,3 +405,65 @@ class TestUnverifiedDeliveryIsRecordedOnTheJob:
def test_scheduler_module_exposes_the_confirmation_helper():
"""Guard the import surface the delivery block depends on."""
assert callable(sched_delivery._confirm_adapter_delivery)
+
+
+class TestStandaloneSendIsBounded:
+ """The standalone fallback lane must not wait on its send unbounded (#115469).
+
+ ``_send_to_platform``'s gateway-loop dispatch awaits with a deliberate
+ no-timeout shield whose comment assumes an outer ``_run_async`` bound — but
+ this lane's outer runner is a bare ``asyncio.run``, so a mid-reconnect
+ transport pinned the run (and the restart drain behind it) for hours while
+ the job's script had finished in seconds.
+ """
+
+ def _target(self):
+ return sched_delivery._TargetDelivery(
+ job=_job(), platform=None, platform_name="telegram", chat_id=CHAT_ID,
+ thread_id=None, transport=None, pconfig=None, runtime_adapter=None,
+ target_adapters=None, config=None, loop=None, notify_delivery=False,
+ origin={}, origin_target=False, origin_user_id=None, is_dm_target=False,
+ mirror_text="", mirror_this_target=False, in_channel_surface=False,
+ inchannel_continuable=False, opened_thread_id=None)
+
+ def test_hung_send_is_released_at_the_bound(self, monkeypatch, caplog):
+ async def _hang(*_args, **_kwargs):
+ await asyncio.sleep(3600)
+
+ monkeypatch.setattr("tools.send_message_tool._send_to_platform", _hang)
+ monkeypatch.setattr(sched_delivery, "_get_standalone_send_timeout", lambda: 0.2)
+
+ with caplog.at_level(logging.INFO, logger="cron.scheduler"):
+ started = time.monotonic()
+ result, error = sched_delivery._standalone_send(self._target(), "Nightly report.", [])
+
+ assert result is None
+ assert error is not None
+ assert "timed out after 0.2s" in error
+ assert "in flight" in error # an un-cancelled shielded send may still land
+ assert time.monotonic() - started < 30 # released at the bound, not the coroutine's hour
+ assert "timed out" in caplog.text
+
+ def test_a_timely_send_is_unaffected(self, monkeypatch):
+ async def _ok(*_args, **_kwargs):
+ return {"success": True, "message_id": 7}
+
+ monkeypatch.setattr("tools.send_message_tool._send_to_platform", _ok)
+ monkeypatch.setattr(sched_delivery, "_get_standalone_send_timeout", lambda: 30)
+
+ result, error = sched_delivery._standalone_send(self._target(), "Nightly report.", [])
+
+ assert error is None
+ assert result == {"success": True, "message_id": 7}
+
+ def test_timeout_default_and_config_override(self, monkeypatch):
+ monkeypatch.setattr(sched, "load_config", lambda: {})
+ assert sched_delivery._get_standalone_send_timeout() == 60
+
+ monkeypatch.setattr(sched, "load_config",
+ lambda: {"cron": {"standalone_send_timeout_seconds": 5}})
+ assert sched_delivery._get_standalone_send_timeout() == 5
+
+ monkeypatch.setattr(sched, "load_config",
+ lambda: {"cron": {"standalone_send_timeout_seconds": -1}})
+ assert sched_delivery._get_standalone_send_timeout() == 60