JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix:/cron建立多个定时任务后删除cron_jobs.json,后端停止运行
openJiuwen-botf09555db73b8
diff --git a/jiuwenswarm/gateway/cron/scheduler.py b/jiuwenswarm/gateway/cron/scheduler.pyindex c86d2907c4..f1c99a12a0 100644--- a/jiuwenswarm/gateway/cron/scheduler.py+++ b/jiuwenswarm/gateway/cron/scheduler.py@@ -298,6 +298,42 @@ class CronSchedulerService:def is_running(self) -> bool:return self._running+ async def _cancel_agent_session(self, state: CronRunState) -> None:+ """Fire-and-forget: 向 AgentServer 发送 CHAT_CANCEL 中断请求。++ 当 cron_jobs.json 被删除或 job 被移除后,gateway 的 asyncio Task+ 被 task.cancel() 取消,但这只终止了 gateway 端等待响应的协程。+ AgentServer 不知道请求已被取消,会继续执行 LLM 调用。此方法+ 主动发送中断请求,让后端也停止处理,彻底消灭"幽灵任务"。+ """+ try:+ interrupt_env = e2a_from_agent_fields(+ request_id=f"cron-cancel-{state.run_id}",+ channel_id="__cron__",+ session_id=f"cron_{state.job_id}",+ req_method=ReqMethod.CHAT_CANCEL,+ params={"cron": {"job_id": state.job_id, "run_id": state.run_id}},+ is_stream=False,+ timestamp=self._now_fn(),+ )+ await self._agent_client.send_request(interrupt_env)+ logger.info(+ "[Cron] AgentServer interrupt sent for ghost task: "+ "job_id=%s run_id=%s",+ state.job_id,+ state.run_id,+ )+ except (OSError, RuntimeError) as exc:+ # Fire-and-forget: 网络断开、连接超时或 AgentServer 不可达+ # 都不影响主流程,只是最佳努力的中断+ logger.warning(+ "[Cron] AgentServer interrupt failed for ghost task "+ "(non-critical): job_id=%s run_id=%s error=%s",+ state.job_id,+ state.run_id,+ exc,+ )+async def start(self) -> None:if self._running:return@@ -351,20 +387,29 @@ class CronSchedulerService:# 取消并清理不再存在于 store 中的运行任务(ghost tasks)。# 这些 task 的 job 已经没有持久化记录了,继续运行只会产生# 无法被用户管理(无 job_id 可删除)的后台任务。+ # 同时向 AgentServer 发送 CHAT_CANCEL 中断请求,否则+ # task.cancel() 只取消 gateway 端的等待协程,AgentServer+ # 仍会继续执行 LLM 请求(用户看到的"后台还在派发"现象)。ghost_run_ids = [rid for rid, state in self._runs.items()if state.job_id not in new_job_ids]for rid in ghost_run_ids:+ state = self._runs[rid]task = self._run_tasks.pop(rid, None)if task is not None and not task.done():logger.info("[Cron] cancelling ghost run task: job_id=%s run_id=%s ""(job no longer in store)",- self._runs[rid].job_id,+ state.job_id,rid,)task.cancel()+ # 向 AgentServer 发送 fire-and-forget 中断请求,让后端真正停止 LLM 处理+ asyncio.create_task(+ self._cancel_agent_session(state),+ name=f"cron-ghost-cancel-{state.job_id}",+ )self._runs.pop(rid, None)now = self._now_fn()@@ -653,16 +698,25 @@ class CronSchedulerService:except asyncio.CancelledError:state.status = "failed"state.error = "cancelled"+ # Ghost task: cancelled by reload because job no longer in store.+ # Do NOT schedule push_update — the user has removed this job and+ # should not see any result from it. Raising CancelledError here+ # so the finally block can detect it via state.error == "cancelled"+ # and skip push_update scheduling.raiseexcept Exception as exc: # noqa: BLE001state.status = "failed"state.error = str(exc)finally:state.finished_at = self._now_fn()- # Ensure failed runs also produce result_text so push logic can deliver it- if not state.result_text and state.error:+ is_cancelled_ghost = state.error == "cancelled"+ should_deliver_result = bool(state.result_text) and not is_cancelled_ghost+ # Ensure failed runs also produce result_text so push logic can deliver it.+ # But for cancelled ghost tasks, skip — no result should be pushed for+ # a job the user has removed.+ if not state.result_text and state.error and not is_cancelled_ghost:state.result_text = f"[cron] 任务执行失败: {state.error}"- if not state.pushed_final and state.result_text:+ if not state.pushed_final and state.result_text and not is_cancelled_ghost:logger.info("[Cron] scheduling push_update after agent finished ""job=%s run_id=%s text_len=%d",@@ -726,7 +780,7 @@ class CronSchedulerService:getattr(envelope, "request_id", ""),exec_session_id,)- except Exception as exc: # noqa: BLE001+ except (OSError, RuntimeError, ValueError) as exc:logger.warning("[Cron] failed to cancel team agent session request_id=%s session_id=%s error=%s",getattr(envelope, "request_id", ""),diff --git a/tests/unit_tests/gateway/test_cron_scheduler.py b/tests/unit_tests/gateway/test_cron_scheduler.pyindex 49f81c59f7..dcf5a2609b 100644--- a/tests/unit_tests/gateway/test_cron_scheduler.py+++ b/tests/unit_tests/gateway/test_cron_scheduler.py@@ -624,6 +624,243 @@ class TestReloadGhostTaskCleanup:assert len(push_update_events_after) == 0+# ── Ghost task CancelledError: no push_update scheduling ──────────────────────────+++class TestGhostTaskCancelledNoPushUpdate:+ """Cancelled ghost task must not schedule push_update in finally block."""++ @pytest.mark.asyncio+ async def test_cancelled_ghost_task_does_not_schedule_push_update(self, tmp_path):+ """Cancelled _run_agent must not schedule push_update in finally block."""+ store_file = tmp_path / "cron_jobs.json"+ store = CronJobStore(path=store_file)+ job = await _create_one_job(store)++ handler = FakeMessageHandler()+ svc = _make_scheduler(store, handler)+ await svc.reload()++ # Create a run state with placeholder_sent = True (triggers push_update+ # in finally when result_text becomes non-empty)+ run_id = f"{job.id}:1234"+ svc.runs[run_id] = CronRunState(+ run_id=run_id,+ job_id=job.id,+ wake_at_iso="2026-06-09T08:55:00+08:00",+ push_at_iso="2026-06-09T09:00:00+08:00",+ job_name=job.name,+ targets=job.targets,+ session_id=None,+ chat_type=None,+ timezone=job.timezone,+ status="running",+ placeholder_sent=True,+ )++ # Count push_update events before+ push_update_before = [+ ev for _, _, ev in svc.events if ev.kind == "push_update"+ ]++ # Delete store file then reload — cancels the ghost task+ store_file.unlink()+ await svc.reload()++ # After reload, ghost run is gone — no new push_update events for it+ push_update_after = [+ ev for _, _, ev in svc.events if ev.kind == "push_update"+ ]+ # push_update count should not increase (ghost task finally skipped)+ assert len(push_update_after) <= len(push_update_before)++ @pytest.mark.asyncio+ async def test_cancelled_task_finally_skips_result_text_and_push(self, tmp_path):+ """state.error == "cancelled" should prevent result_text and push_update."""+ store_file = tmp_path / "cron_jobs.json"+ store = CronJobStore(path=store_file)+ job = await _create_one_job(store)++ handler = FakeMessageHandler()+ svc = _make_scheduler(store, handler)+ await svc.reload()++ run_id = f"{job.id}:1234"+ state = CronRunState(+ run_id=run_id,+ job_id=job.id,+ wake_at_iso="2026-06-09T08:55:00+08:00",+ push_at_iso="2026-06-09T09:00:00+08:00",+ job_name=job.name,+ targets=job.targets,+ session_id=None,+ chat_type=None,+ timezone=job.timezone,+ status="running",+ placeholder_sent=True,+ )++ # Simulate CancelledError in _run_agent: state.error = "cancelled"+ state.error = "cancelled"++ # The finally block logic uses `is_cancelled_ghost = state.error == "cancelled"`+ # to skip push_update. Verify the flag works correctly:+ # Even with placeholder_sent=True, cancelled ghost should not push.+ is_cancelled_ghost = state.error == "cancelled"+ assert is_cancelled_ghost is True++ # result_text should NOT be set for cancelled ghost (finally block check)+ # (In real code: `if not state.result_text and state.error and not is_cancelled_ghost`)+ if not state.result_text and state.error and not is_cancelled_ghost:+ state.result_text = f"[cron] 任务执行失败: {state.error}"++ assert state.result_text is None # No result_text for ghost+++# ── Ghost task CHAT_CANCEL notification ────────────────────────────────────────────+++class TestGhostTaskAgentCancelNotification:+ """Ghost task cancellation must send CHAT_CANCEL to AgentServer."""++ @pytest.mark.asyncio+ async def test_reload_sends_cancel_to_agent_for_ghost_tasks(self, tmp_path):+ """Ghost task cancellation should fire CHAT_CANCEL to AgentServer."""+ store_file = tmp_path / "cron_jobs.json"+ store = CronJobStore(path=store_file)+ job = await _create_one_job(store)++ # Use a FakeAgentClient that records all requests+ cancel_requests = []++ class RecordingAgentClient:+ async def send_request(self, envelope):+ # Record the envelope for later inspection+ cancel_requests.append(envelope)+ return {"content": {"output": "cancelled", "result_type": "answer"}}++ handler = FakeMessageHandler()+ svc = _TestableScheduler(+ store=store,+ agent_client=RecordingAgentClient(),+ message_handler=handler,+ )+ await svc.reload()++ # Simulate a running task+ run_id = f"{job.id}:1234"+ svc.runs[run_id] = CronRunState(+ run_id=run_id,+ job_id=job.id,+ wake_at_iso="2026-06-09T08:55:00+08:00",+ push_at_iso="2026-06-09T09:00:00+08:00",+ job_name=job.name,+ targets=job.targets,+ session_id=None,+ chat_type=None,+ timezone=job.timezone,+ status="running",+ )++ # Create a blocking asyncio Task (simulating agent execution)+ block_event = asyncio.Event()++ async def _long_running():+ await block_event.wait()++ task = asyncio.create_task(_long_running(), name=f"cron-run-{job.id}")+ svc.run_tasks[run_id] = task++ # Delete store file — job gone from store+ store_file.unlink()++ # Reload should cancel ghost task AND send CHAT_CANCEL+ await svc.reload()++ # Give the event loop a turn for the fire-and-forget cancel task to execute+ await asyncio.sleep(0.1)++ # Verify CHAT_CANCEL was sent to AgentServer+ # The cancel request should have method = "chat.interrupt"+ cancel_envelopes = [+ e for e in cancel_requests+ if hasattr(e, "method") and e.method == "chat.interrupt"+ ]+ assert len(cancel_envelopes) >= 1, (+ f"Expected at least 1 CHAT_CANCEL request, got {len(cancel_envelopes)} "+ f"out of {len(cancel_requests)} total requests"+ )++ # Verify the cancel envelope has the correct job context+ cancel_env = cancel_envelopes[0]+ assert hasattr(cancel_env, "params")+ assert "cron" in (cancel_env.params or {})+ assert cancel_env.params["cron"]["job_id"] == job.id+ assert cancel_env.params["cron"]["run_id"] == run_id++ # Cleanup+ block_event.set()++ @pytest.mark.asyncio+ async def test_no_cancel_sent_when_task_already_done(self, tmp_path):+ """If the ghost task is already done, no CHAT_CANCEL should be sent."""+ store_file = tmp_path / "cron_jobs.json"+ store = CronJobStore(path=store_file)+ job = await _create_one_job(store)++ cancel_requests = []++ class RecordingAgentClient:+ async def send_request(self, envelope):+ cancel_requests.append(envelope)+ return {"content": {"output": "done", "result_type": "answer"}}++ handler = FakeMessageHandler()+ svc = _TestableScheduler(+ store=store,+ agent_client=RecordingAgentClient(),+ message_handler=handler,+ )+ await svc.reload()++ run_id = f"{job.id}:1234"+ svc.runs[run_id] = CronRunState(+ run_id=run_id,+ job_id=job.id,+ wake_at_iso="2026-06-09T08:55:00+08:00",+ push_at_iso="2026-06-09T09:00:00+08:00",+ job_name=job.name,+ targets=job.targets,+ session_id=None,+ chat_type=None,+ timezone=job.timezone,+ status="succeeded",+ )++ # Create a task that's already done (completed immediately)+ async def _instant_task():+ return "done"++ task = asyncio.create_task(_instant_task(), name=f"cron-run-{job.id}")+ # Wait for it to finish+ await task+ assert task.done()+ svc.run_tasks[run_id] = task++ # Delete store file — job gone from store+ store_file.unlink()++ # Reload should NOT send CHAT_CANCEL because task is already done+ await svc.reload()+ await asyncio.sleep(0.1)++ cancel_envelopes = [+ e for e in cancel_requests+ if hasattr(e, "method") and e.method == "chat.interrupt"+ ]+ assert len(cancel_envelopes) == 0++# ── Team mode execution ──────────────────────────────────────────────────────@@ -1074,4 +1311,4 @@ class TestCronBroadcastText:job_name="agent-core-commit-review",text="[cron] 任务执行超时(>10min)",is_placeholder=False,- ) == "[cron] 任务执行超时(>10min)"\ No newline at end of file+ ) == "[cron] 任务执行超时(>10min)"