Skip to content

The agent that grows with you

fix(cron): bound the standalone send inside the coroutine so the thread fallback keeps it

teknium1729b1c3d56c0
diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.py
index 5dea07c350b..bcc0285551b 100644
--- a/cron/scheduler_delivery.py
+++ b/cron/scheduler_delivery.py
@@ -1669,10 +1669,14 @@ def _standalone_send(
job = t.job
shutdown_msg = f"delivery to {t.where} skipped — interpreter is shutting down"
- def _send():
- return _send_to_platform(
+ send_timeout = _get_standalone_send_timeout()
+
+ async def _send():
+ # The bound lives inside the coroutine: the running-loop fallback below closes ``coro``
+ # unstarted, and a wait_for wrapper created out here would be left never awaited.
+ return await asyncio.wait_for(_send_to_platform(
t.platform, t.pconfig, t.chat_id, content, thread_id=t.thread_id,
- media_files=media_files)
+ media_files=media_files), timeout=send_timeout)
def _warned(msg: str) -> tuple[None, str]:
logger.warning("Job '%s': %s", job["id"], msg)
@@ -1692,9 +1696,8 @@ 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(asyncio.wait_for(coro, timeout=send_timeout)), None
+ return asyncio.run(coro), 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).
diff --git a/tests/cron/test_cron_live_delivery_confirmation.py b/tests/cron/test_cron_live_delivery_confirmation.py
index b1f8964b351..080c247a8b4 100644
--- a/tests/cron/test_cron_live_delivery_confirmation.py
+++ b/tests/cron/test_cron_live_delivery_confirmation.py
@@ -410,60 +410,42 @@ def test_scheduler_module_exposes_the_confirmation_helper():
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.
+ ``_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):
+ @staticmethod
+ def _deliver_standalone(sender, cron_cfg):
+ """Drive the production entry point with no live adapters (the standalone lane)."""
+ with patch("gateway.config.load_gateway_config", return_value=_gateway_config()), \
+ patch("cron.scheduler.load_config",
+ return_value={"cron": {"wrap_response": False, **cron_cfg}}), \
+ patch("cron.scheduler_delivery._record_delivery_verification"), \
+ patch("tools.send_message_tool._send_to_platform", sender):
+ return _deliver_result(_job(), "Nightly report.")
+
+ def test_hung_send_is_released_at_the_configured_bound(self, 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)
+ await asyncio.Event().wait() # transport mid-reconnect: the send never resolves
with caplog.at_level(logging.INFO, logger="cron.scheduler"):
started = time.monotonic()
- result, error = sched_delivery._standalone_send(self._target(), "Nightly report.", [])
+ error = self._deliver_standalone(_hang, {"standalone_send_timeout_seconds": 1})
- assert result is None
+ assert time.monotonic() - started < 30 # released at the bound, not never
assert error is not None
- assert "timed out after 0.2s" in error
+ assert "timed out after 1s" 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
+ assert "via live adapter" not in caplog.text and "delivered to" not in caplog.text
- def test_a_timely_send_is_unaffected(self, monkeypatch):
+ def test_a_timely_send_is_unaffected(self, caplog):
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.", [])
+ with caplog.at_level(logging.INFO, logger="cron.scheduler"):
+ error = self._deliver_standalone(_ok, {})
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
+ assert f"delivered to telegram:{CHAT_ID}" in caplog.text
diff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.md
index bbc9e6678f4..69607d55995 100644
--- a/website/docs/user-guide/features/cron.md
+++ b/website/docs/user-guide/features/cron.md
@@ -876,6 +876,18 @@ A timed-out delivery is recorded in `last_delivery_error`; the bot's turn may st
The cap bounds the bot's **turn** only. When that turn messages a teammate (`message_agent`), the delivery process stays alive afterwards — bounded by `terminal.oneshot_completion_wait_seconds` — so the teammate's reply can land in the Bot Chat; that wait is not part of the delivery and is never counted against, or cut short by, this cap.
+## Standalone send timeout
+
+When the live gateway adapter cannot deliver (or no gateway is running), a target is sent through the platform's standalone sender. That send is bounded by a wall-clock timeout — 60 seconds by default — so a transport that is mid-reconnect cannot pin the job run (and a pending restart drain behind it) indefinitely:
+
+```yaml
+# ~/.hermes/config.yaml
+cron:
+ standalone_send_timeout_seconds: 120
+```
+
+A timed-out send is recorded in `last_delivery_error` as `standalone send to <target> timed out after Ns`; the message may still land if the adapter had already accepted it.
+
## No-agent mode (script-only jobs)
For recurring jobs that don't need LLM reasoning — classic watchdogs, disk/memory alerts, heartbeats, CI pings — pass `no_agent=True` at creation time. The scheduler runs your script on schedule and delivers its stdout directly, skipping the agent entirely: