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-botcf289e471a89
diff --git a/jiuwenswarm/gateway/cron/scheduler.py b/jiuwenswarm/gateway/cron/scheduler.pyindex 627ccfc497..c713c43f4b 100644--- a/jiuwenswarm/gateway/cron/scheduler.py+++ b/jiuwenswarm/gateway/cron/scheduler.py@@ -159,20 +159,50 @@ class CronSchedulerService:logger.info("[Cron] scheduler stopped")async def reload(self) -> None:- """Reload jobs from store and rebuild the event queue."""+ """Reload jobs from store and rebuild the event queue.++ When the store is empty (e.g. cron_jobs.json was deleted externally),+ all in-memory running tasks for jobs that no longer exist in the store+ are cancelled and their state cleaned up, preventing "ghost" tasks that+ continue executing and pushing results despite having no persistent record.+ """jobs = await self._store.list_jobs()self._jobs = {j.id: j for j in jobs}- # 保留飞行中的 push_update 事件(单次任务 push 后即 disabled,但补发结果还未完成)+ new_job_ids = set(self._jobs.keys())++ # 保留飞行中的 push_update 事件,但仅限于仍存在于 store 中的 job。+ # 不存在的 job 的 push_update 不应继续推送:store 已无记录意味着+ # 用户已明确删除了这些任务(或删除了整个文件),它们的运行结果+ # 也应该中止,否则会形成"幽灵任务"——/cron 显示无任务但后台仍在推送。pending_push_updates = [(at_ts, seq, ev)for at_ts, seq, ev in self._events- if ev.kind == "push_update"+ if ev.kind == "push_update" and ev.job_id in new_job_ids]self._events.clear()self._seq = 0for item in pending_push_updates:heapq.heappush(self._events, item)+ # 取消并清理不再存在于 store 中的运行任务(ghost tasks)。+ # 这些 task 的 job 已经没有持久化记录了,继续运行只会产生+ # 无法被用户管理(无 job_id 可删除)的后台任务。+ 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:+ 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,+ rid,+ )+ task.cancel()+ self._runs.pop(rid, None)+now = self._now_fn()for job in jobs:if not job.enabled:@@ -287,20 +317,36 @@ class CronSchedulerService:job = self._jobs.get(ev.job_id)if job is None and ev.kind != "push_update":return- # For wake/push events: if the job exists in memory but no longer- # exists in the persistent store (e.g. cron_jobs.json was deleted),- # skip execution and reload to clear stale in-memory data.- if ev.kind in ("wake", "push") and job is not None:- store_job = await self._store.get_job(ev.job_id)- if store_job is None:+ # For wake/push/push_update events: if the job no longer exists in the+ # persistent store (e.g. cron_jobs.json was deleted), skip execution.+ # This prevents "ghost tasks" — tasks that continue running and pushing+ # results even though the user sees no tasks in /cron and has no job_id+ # to manage or delete them.+ # Note: push_update was previously exempted to deliver already-computed+ # results, but that exemption creates the ghost task problem. When the+ # store is gone, the job is gone, and its results should not be pushed.+ store_job = await self._store.get_job(ev.job_id)+ if store_job is None:+ # If job was in memory but not in store, reload to clear stale data+ if ev.kind in ("wake", "push") and job is not None:logger.info("[Cron] job %s no longer in store (file may have been deleted), ""skipping event %s and triggering reload",ev.job_id, ev.kind,)await self.reload()- return+ elif ev.kind == "push_update":+ logger.info(+ "[Cron] push_update skipped: job %s no longer in store "+ "(file may have been deleted), skipping ghost push job_id=%s run_id=%s",+ ev.job_id, ev.job_id, ev.run_id,+ )+ returnif job is None and ev.kind == "push_update":+ # Job not in _jobs but still in store (e.g. disabled/expired job):+ # rebuild from state for routing purposes. This is legitimate —+ # push_update for a disabled one-shot job that's still in the store+ # must still deliver its result.state = self._runs.get(ev.run_id)if state is None:logger.info("[Cron] push_update skipped: no state and no job job_id=%s run_id=%s", ev.job_id, ev.run_id)diff --git a/tests/unit_tests/gateway/test_cron_scheduler.py b/tests/unit_tests/gateway/test_cron_scheduler.pyindex e3db4b1d31..1c331a9b0d 100644--- a/tests/unit_tests/gateway/test_cron_scheduler.py+++ b/tests/unit_tests/gateway/test_cron_scheduler.py@@ -42,6 +42,20 @@ class _TestableScheduler(CronSchedulerService):def runs(self):return self._runs+ @property+ def run_tasks(self):+ """Expose _run_tasks for test assertions (G.CLS.11: access via subclass property)."""+ return self._run_tasks++ def schedule_event(self, at_dt, kind, job_id, run_id):+ """Expose _schedule_event for test use (G.CLS.11: access via subclass wrapper)."""+ return self._schedule_event(at_dt, kind, job_id, run_id)++ @property+ def events(self):+ """Expose _events for test assertions (G.CLS.11: access via subclass property)."""+ return self._events+def _make_job(job_id="job-1", name="test", **overrides):"""Build a CronJob with sensible defaults for testing."""@@ -239,9 +253,11 @@ class TestHandleEventStoreValidation:assert len(handler.published) == 0@pytest.mark.asyncio- async def test_push_update_not_skipped_when_job_absent(self, tmp_path):- # push_update must always proceed — it delivers results of- # already-triggered runs that must not be lost.+ async def test_push_update_skipped_when_job_absent_from_store(self, tmp_path):+ # When cron_jobs.json is deleted, push_update should also be skipped.+ # Continuing to push results for a job that no longer exists in the store+ # creates "ghost tasks" — the user sees /cron showing no tasks but+ # messages are still being pushed, and there's no job_id to delete them.store_file = tmp_path / "cron_jobs.json"store = CronJobStore(path=store_file)job = await _create_one_job(store)@@ -271,7 +287,40 @@ class TestHandleEventStoreValidation:ev = _Event(at_ts=time.time(), seq=1, kind="push_update", job_id=job.id, run_id=run_id)await svc.handle_event(ev)- # push_update still delivered even though store file is gone+ # push_update should be skipped: no ghost pushes for absent jobs+ assert len(handler.published) == 0++ @pytest.mark.asyncio+ async def test_push_update_delivered_when_job_present_in_store(self, tmp_path):+ # push_update should proceed normally when the job still exists in the store.+ 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()++ # Simulate a completed run with a result to deliver+ 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,+ result_text="result: 9am now",+ )++ # Store file still exists+ ev = _Event(at_ts=time.time(), seq=1, kind="push_update", job_id=job.id, run_id=run_id)+ await svc.handle_event(ev)++ # push_update delivered successfullyassert len(handler.published) == 1@pytest.mark.asyncio@@ -295,4 +344,143 @@ class TestHandleEventStoreValidation:await svc.handle_event(ev)assert wake_called is True- assert len(svc.jobs) == 1\ No newline at end of file+ assert len(svc.jobs) == 1+++# ── Reload ghost task cleanup ─────────────────────────────────────────────────+++class TestReloadGhostTaskCleanup:+ """reload() cancels running tasks and clears state for jobs no longer in the store."""++ @pytest.mark.asyncio+ async def test_reload_cancels_ghost_run_tasks_when_store_deleted(self, tmp_path):+ """Reload cancels in-flight tasks for absent jobs and clears _runs state."""+ 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()++ # Simulate a running task: create state + an asyncio Task that blocks+ 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 long-running 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++ # Verify preconditions: run state and task exist+ assert run_id in svc.runs+ assert run_id in svc.run_tasks+ assert not task.done()++ # Delete the store file — job no longer exists persistently+ store_file.unlink()++ # Trigger reload (which _check_store_changed would do)+ await svc.reload()++ # Ghost task should be cancelled and removed from run_tasks+ assert run_id not in svc.run_tasks+ # task.cancel() is a request — the task needs a yield point to process it.+ # Give the event loop a turn to propagate the cancellation.+ await asyncio.sleep(0)+ assert task.cancelled() or task.done()+ # Ghost run state should be removed from _runs+ assert run_id not in svc.runs+ # No jobs in memory+ assert len(svc.jobs) == 0+ # No messages published for the ghost task+ assert len(handler.published) == 0++ # Cleanup+ block_event.set()++ @pytest.mark.asyncio+ async def test_reload_preserves_running_tasks_for_existing_jobs(self, tmp_path):+ """In-flight tasks for jobs still in store should NOT be cancelled on reload."""+ 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()++ # 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",+ result_text="task finished",+ )++ # Store file still exists — job is still in the store+ await svc.reload()++ # Running task for existing job should be preserved+ assert run_id in svc.runs+ assert len(svc.jobs) == 1++ @pytest.mark.asyncio+ async def test_reload_cleans_push_update_events_for_ghost_jobs(self, tmp_path):+ """Push_update events for absent jobs should be removed during reload."""+ 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()++ # Schedule a push_update event+ run_id = f"{job.id}:1234"+ from datetime import datetime+ from zoneinfo import ZoneInfo+ svc.schedule_event(+ datetime.now(tz=ZoneInfo("Asia/Shanghai")),+ "push_update", job.id, run_id,+ )++ # Verify push_update event exists+ push_update_events = [+ ev for _, _, ev in svc.events if ev.kind == "push_update"+ ]+ assert len(push_update_events) == 1++ # Delete the store file — job gone from store+ store_file.unlink()++ # Reload should remove push_update events for the ghost job+ await svc.reload()++ push_update_events_after = [+ ev for _, _, ev in svc.events if ev.kind == "push_update"+ ]+ assert len(push_update_events_after) == 0\ No newline at end of file