The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): deliver interrupted-cron notices before adapters disconnect
joaomarcosbaf70348509a
diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 552fa848c75..0ba5ca804e7 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -5852,6 +5852,23 @@ def _run_one_job_body(interrupted = _consume_interrupted_flag(job["id"], execution_token)if interrupted:+ if delivery_error:+ # The gateway shutdown already wrote last_status for this run,+ # so mark_job_run is skipped below — but it could not know that+ # the notice we just tried to send never left the process (the+ # adapters were torn down first, #82232). Record the delivery+ # failure on its own via update_job: mark_job_run also advances+ # next_run_at and the repeat counter, and running that a second+ # time for one run would skip a fire or auto-delete the job+ # early.+ try:+ from cron.jobs import update_job+ update_job(job["id"], {"last_delivery_error": delivery_error})+ except Exception as _rec_err:+ logger.debug(+ "Failed recording delivery_error for interrupted job %s: %s",+ job["id"], _rec_err,+ )finish_execution(execution_id,success=False,diff --git a/gateway/run.py b/gateway/run.pyindex d433e443591..1c2985712e0 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -10171,6 +10171,103 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewif interrupted_api:logger.debug("Interrupted %d api_server run(s) during shutdown", interrupted_api)+ async def _notify_interrupted_cron_jobs(self, job_ids) -> int:+ """Tell the owner of each just-interrupted cron job that its run died.++ The cron worker cannot do this itself. Its thread reaches+ ``_deliver_result`` asynchronously, and by then+ ``_bounded_adapter_teardown`` has closed the transport — so the notice+ never leaves the process, and ``_consume_interrupted_flag`` discards+ the resulting ``delivery_error`` along with it. The run's only trace is+ a line in jobs.json nobody reads (#82232).++ Must therefore be called from the post-interrupt phase, while adapters+ are still connected — the same window+ ``_notify_active_sessions_of_shutdown`` relies on for chat sessions,+ which is blind to cron work because cron runs on the scheduler's own+ thread pool rather than ``self._running_agents`` (#60432).++ Best-effort by construction: every failure is swallowed so a wedged+ adapter can never extend shutdown. Returns the number of notices sent.+ """+ if not job_ids:+ return 0+ try:+ from cron.jobs import get_job+ from cron.scheduler import _resolve_delivery_targets+ except Exception as e:+ logger.debug("Cron interrupt notification unavailable: %s", e)+ return 0++ action = "restarting" if self._restart_requested else "shutting down"+ notified: set = set()+ for job_id in job_ids:+ try:+ job = get_job(job_id)+ if not job:+ continue+ # deliver=local jobs — and deliver=origin jobs with no+ # resolvable origin (#43014) — resolve to zero targets and+ # must stay silent rather than fall back to a home channel.+ targets = _resolve_delivery_targets(job)+ except Exception as e:+ logger.debug("Cron interrupt targets unresolved for %s: %s", job_id, e)+ continue+ if not targets:+ continue++ msg = (+ f"⚠️ Cron job '{job.get('name') or job_id}' was interrupted — "+ f"the gateway is {action} and killed the run before it "+ "finished. No result was produced for this run."+ )+ for target in targets:+ try:+ platform = Platform(str(target.get("platform", "")).lower())+ except Exception:+ continue+ adapter = self.adapters.get(platform)+ if adapter is None:+ continue+ platform_cfg = self.config.platforms.get(platform)+ if platform_cfg is not None and not platform_cfg.gateway_restart_notification:+ continue++ chat_id = str(target.get("chat_id"))+ thread_id = target.get("thread_id")+ dedup_key = (+ job_id,+ platform.value,+ chat_id,+ str(thread_id) if thread_id else None,+ )+ if dedup_key in notified:+ continue+ try:+ metadata = self._thread_metadata_for_target(+ platform, chat_id, thread_id, adapter=adapter+ )+ result = await adapter.send(chat_id, msg, metadata=metadata)+ if result is not None and getattr(result, "success", True) is False:+ logger.debug(+ "Cron interrupt notice to %s:%s failed: %s",+ platform.value, chat_id,+ getattr(result, "error", "send returned success=False"),+ )+ continue+ notified.add(dedup_key)+ except Exception as e:+ logger.debug(+ "Cron interrupt notice to %s:%s raised: %s",+ platform.value, chat_id, e,+ )+ if notified:+ logger.info(+ "Shutdown: delivered %d interrupted-cron-job notice(s)",+ len(notified),+ )+ return len(notified)+async def _notify_active_sessions_of_shutdown(self) -> None:"""Send shutdown/restart notifications to active chats and home channels.@@ -13784,9 +13881,13 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewreturnasync def _stop_impl() -> None:- def _kill_tool_subprocesses(phase: str) -> None:+ def _kill_tool_subprocesses(phase: str) -> list:"""Kill tool subprocesses + tear down terminal envs + browsers.+ Returns the cron job IDs this phase marked interrupted, so the+ caller can notify their owners while adapters are still up+ (#82232). Empty list when no cron work was in flight.+Called twice in the shutdown path: once eagerly after adrain timeout forces agent interrupt (so we reclaim bash/sleep children before systemd TimeoutStopSec escalates to@@ -13807,6 +13908,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew)except Exception as _e:logger.debug("process_registry.kill_all (%s) error: %s", phase, _e)+ _marked_cron_jobs: list = []try:# Any cron job still dispatched at this instant just had# its tool subprocess killed above (kill_all() has no@@ -13817,7 +13919,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew# the scheduler can never report that as success (#60432).# No-op when no cron job is in flight.from cron.scheduler import mark_running_jobs_interrupted- _interrupted = mark_running_jobs_interrupted(+ _interrupted = _marked_cron_jobs = mark_running_jobs_interrupted(f"Gateway shutdown ({phase}) killed the job's tool ""subprocess before the run finished.")@@ -13848,6 +13950,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewcleanup_all_browsers()except Exception as _e:logger.debug("cleanup_all_browsers (%s) error: %s", phase, _e)+ return _marked_cron_jobs# Thread-based shutdown watchdog (#66892): asyncio timeouts cannot# recover a frozen loop. Arm a plain OS thread at the start of@@ -14090,11 +14193,23 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew# children left behind by an interrupted terminal tool get# killed by systemd instead of us (issue #8202). The final# catch-all cleanup below still runs for the graceful path.- _kill_tool_subprocesses("post-interrupt")+ _interrupted_cron_jobs = _kill_tool_subprocesses("post-interrupt")logger.info("Shutdown phase: post-interrupt tool kill done at +%.2fs",_phase_elapsed(),)+ # Last window where the transport is still up. The cron worker+ # whose run we just killed will try to deliver its own+ # "interrupted" notice, but it gets there after the adapter+ # teardown below and the message is lost (#82232).+ try:+ await self._notify_interrupted_cron_jobs(_interrupted_cron_jobs)+ except Exception as _e:+ logger.debug("Cron interrupt notification failed: %s", _e)+ logger.info(+ "Shutdown phase: cron interrupt notices done at +%.2fs",+ _phase_elapsed(),+ )if self._restart_requested and self._restart_detached:try:diff --git a/tests/gateway/test_cron_interrupt_notification.py b/tests/gateway/test_cron_interrupt_notification.pynew file mode 100644index 00000000000..91a73093120--- /dev/null+++ b/tests/gateway/test_cron_interrupt_notification.py@@ -0,0 +1,229 @@+"""Regression tests for #82232.++When the shutdown interrupts an in-flight cron job, the job's own worker+thread tries to deliver an "interrupted" notice — and loses, because+``_bounded_adapter_teardown`` has already closed the transport by the time it+gets there. The notice is dropped, and ``_consume_interrupted_flag`` discards+the resulting ``delivery_error`` with it, so the run's only trace is a line in+jobs.json.++The gateway now sends that notice itself in the post-interrupt phase, while+adapters are still connected — the same window+``_notify_active_sessions_of_shutdown`` uses for chat sessions, which never+saw cron work because cron runs outside ``_running_agents`` (#60432).+"""++from unittest.mock import patch++import pytest++from gateway.config import Platform+from tests.gateway.restart_test_helpers import make_restart_runner++[email protected](autouse=True)+def _reset_cron_running_set():+ import cron.scheduler as sched++ sched._running_job_ids.clear()+ sched._interrupted_job_ids.clear()+ yield+ sched._running_job_ids.clear()+ sched._interrupted_job_ids.clear()+++def _telegram_job(job_id="be62d36a9914", name="daily-digest", chat_id="123456"):+ return {+ "id": job_id,+ "name": name,+ "deliver": f"telegram:{chat_id}",+ }+++def _telegram_target(chat_id="123456"):+ return {"platform": "telegram", "chat_id": chat_id, "thread_id": None}+++def _bind_notifier(runner):+ from gateway.run import GatewayRunner++ runner._notify_interrupted_cron_jobs = (+ GatewayRunner._notify_interrupted_cron_jobs.__get__(runner, GatewayRunner)+ )+ runner._thread_metadata_for_target = (+ GatewayRunner._thread_metadata_for_target.__get__(runner, GatewayRunner)+ )+ return runner+++class TestNotifyInterruptedCronJobs:+ @pytest.mark.asyncio+ async def test_owner_is_told_the_run_was_killed(self):+ runner, adapter = make_restart_runner()+ _bind_notifier(runner)+ job = _telegram_job()++ with patch("cron.jobs.get_job", return_value=job), \+ patch("cron.scheduler._resolve_delivery_targets",+ return_value=[_telegram_target()]):+ sent = await runner._notify_interrupted_cron_jobs([job["id"]])++ assert sent == 1+ assert len(adapter.sent) == 1+ body = adapter.sent[0]+ assert "daily-digest" in body+ assert "interrupted" in body.lower()+ assert adapter.sent_calls[0][0] == "123456"++ @pytest.mark.asyncio+ async def test_says_restarting_when_restart_was_requested(self):+ runner, adapter = make_restart_runner()+ _bind_notifier(runner)+ runner._restart_requested = True+ job = _telegram_job()++ with patch("cron.jobs.get_job", return_value=job), \+ patch("cron.scheduler._resolve_delivery_targets",+ return_value=[_telegram_target()]):+ await runner._notify_interrupted_cron_jobs([job["id"]])++ assert "restarting" in adapter.sent[0]++ @pytest.mark.asyncio+ async def test_local_only_job_stays_silent(self):+ """deliver=local, and deliver=origin with no resolvable origin+ (#43014), resolve to zero targets and must not fall back to a home+ channel."""+ runner, adapter = make_restart_runner()+ _bind_notifier(runner)+ job = {"id": "j1", "name": "local-job", "deliver": "local"}++ with patch("cron.jobs.get_job", return_value=job), \+ patch("cron.scheduler._resolve_delivery_targets", return_value=[]):+ sent = await runner._notify_interrupted_cron_jobs(["j1"])++ assert sent == 0+ assert adapter.sent == []++ @pytest.mark.asyncio+ async def test_respects_platform_gateway_restart_notification_false(self):+ runner, adapter = make_restart_runner()+ _bind_notifier(runner)+ runner.config.platforms[Platform.TELEGRAM].gateway_restart_notification = False+ job = _telegram_job()++ with patch("cron.jobs.get_job", return_value=job), \+ patch("cron.scheduler._resolve_delivery_targets",+ return_value=[_telegram_target()]):+ sent = await runner._notify_interrupted_cron_jobs([job["id"]])++ assert sent == 0+ assert adapter.sent == []++ @pytest.mark.asyncio+ async def test_empty_job_list_is_a_noop(self):+ runner, adapter = make_restart_runner()+ _bind_notifier(runner)++ assert await runner._notify_interrupted_cron_jobs([]) == 0+ assert adapter.sent == []++ @pytest.mark.asyncio+ async def test_a_raising_adapter_cannot_block_shutdown(self):+ """Best-effort by construction: a wedged adapter must not propagate."""+ runner, adapter = make_restart_runner()+ _bind_notifier(runner)+ job = _telegram_job()++ async def _boom(*_a, **_kw):+ raise RuntimeError("transport already closed")++ adapter.send = _boom++ with patch("cron.jobs.get_job", return_value=job), \+ patch("cron.scheduler._resolve_delivery_targets",+ return_value=[_telegram_target()]):+ sent = await runner._notify_interrupted_cron_jobs([job["id"]])++ assert sent == 0++ @pytest.mark.asyncio+ async def test_duplicate_targets_send_once_per_job(self):+ runner, adapter = make_restart_runner()+ _bind_notifier(runner)+ job = _telegram_job()++ with patch("cron.jobs.get_job", return_value=job), \+ patch("cron.scheduler._resolve_delivery_targets",+ return_value=[_telegram_target(), _telegram_target()]):+ sent = await runner._notify_interrupted_cron_jobs([job["id"]])++ assert sent == 1+ assert len(adapter.sent) == 1+++class TestShutdownDeliversNoticeBeforeDisconnect:+ @pytest.mark.asyncio+ async def test_notice_is_sent_while_the_adapter_is_still_connected(self, monkeypatch):+ """The whole point is ordering: a notice sent after teardown is lost,+ which is the bug."""+ import cron.scheduler as sched+ import tools.browser_tool as _bt+ import tools.process_registry as _pr+ import tools.terminal_tool as _tt++ runner, adapter = make_restart_runner()+ runner._restart_drain_timeout = 0.01 # force the interrupt path+ sched._running_job_ids.add("be62d36a9914")++ monkeypatch.setattr(_pr.process_registry, "kill_all", lambda task_id=None: 1)+ monkeypatch.setattr(_tt, "cleanup_all_environments", lambda: None)+ monkeypatch.setattr(_bt, "cleanup_all_browsers", lambda: None)++ events: list[str] = []+ real_send = adapter.send++ async def _tracking_send(chat_id, content, reply_to=None, metadata=None):+ if "was interrupted" in content:+ events.append("cron_notice")+ return await real_send(chat_id, content, reply_to=reply_to, metadata=metadata)++ async def _tracking_disconnect():+ events.append("disconnect")++ adapter.send = _tracking_send+ adapter.disconnect = _tracking_disconnect++ with patch("gateway.status.remove_pid_file"), \+ patch("gateway.status.write_runtime_status"), \+ patch("cron.scheduler.mark_job_run"), \+ patch("cron.jobs.get_job", return_value=_telegram_job()), \+ patch("cron.scheduler._resolve_delivery_targets",+ return_value=[_telegram_target()]):+ await runner.stop()++ assert "cron_notice" in events, "interrupted-cron notice was never sent"+ assert "disconnect" in events+ assert events.index("cron_notice") < events.index("disconnect"), (+ f"notice sent after adapter teardown — it would be lost: {events}"+ )+++class TestDeliveryErrorIsRecordedWhenTheNoticeCannotBeSent:+ def test_interrupted_run_records_delivery_error_without_mark_job_run(self):+ """``_consume_interrupted_flag`` short-circuits ``mark_job_run``,+ which used to discard ``delivery_error`` along with it. The recovery+ path must use ``update_job`` so the repeat counter and next_run_at+ bookkeeping that ``mark_job_run`` owns is not run twice for one run.+ """+ import inspect++ import cron.scheduler as sched++ src = inspect.getsource(sched.run_one_job)+ assert 'update_job(job["id"], {"last_delivery_error": delivery_error})' in src, (+ "interrupted runs must still persist the delivery failure"+ )+ # The recovery branch hangs off the interrupted-flag short-circuit,+ # not off a second mark_job_run call.+ assert "elif delivery_error:" in src