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
[mirror] openJiuwen-ai/jiuwenswarm#803: fix:cronJobStore的持久化文件的跨进程互斥锁
CUIZIBO1d5c54bdf9cd
diff --git a/jiuwenswarm/gateway/cron/store.py b/jiuwenswarm/gateway/cron/store.pyindex 03c4f12e2f..61b38c5421 100644--- a/jiuwenswarm/gateway/cron/store.py+++ b/jiuwenswarm/gateway/cron/store.py@@ -5,9 +5,12 @@ import jsonimport loggingimport timeimport uuid+from collections.abc import Callablefrom dataclasses import replacefrom pathlib import Path-from typing import Any+from typing import Any, TypeVar++import portalockerfrom jiuwenswarm.gateway.cron.models import (CronJob,@@ -25,6 +28,9 @@ from jiuwenswarm.common.work_mode import (logger = logging.getLogger(__name__)+_T = TypeVar("_T")+_FILE_LOCK_TIMEOUT_SEC = 10.0+# proactive.tick 是由 proactive_cron_sync 自动注册、由 config 开关驱动的任务。# 其 name/enabled/description/wake_offset/targets/mode 均由系统/配置侧维护,# update 时只允许改调度本身(cron_expr/timezone);expired/updated_at 由调度器/内部写。@@ -109,22 +115,49 @@ class _ProactiveJobProtected(RuntimeError):class CronJobStore:- """Persist cron jobs to ~/.jiuwenswarm/agent/home/cron_jobs.json."""+ """Persist cron jobs to ~/.jiuwenswarm/agent/home/cron_jobs.json.- def __init__(self, path: Path | None = None) -> None:+ 并发安全:+ - ``asyncio.Lock``:同进程协程互斥;+ - ``portalocker`` 伴生 ``cron_jobs.json.lock``:跨进程(多 Gateway / Agent)互斥。+ 整个 read-modify-write 在双层锁内完成,避免 lost update。+ """++ def __init__(+ self,+ path: Path | None = None,+ *,+ file_lock_timeout: float = _FILE_LOCK_TIMEOUT_SEC,+ ) -> None:self._path = path or get_cron_jobs_path()self._lock = asyncio.Lock()+ self._file_lock_timeout = float(file_lock_timeout)@propertydef path(self) -> Path:return self._path+ def _call_under_file_lock(self, fn: Callable[[], _T]) -> _T:+ """在伴生 ``cron_jobs.json.lock`` 上拿跨进程锁后执行 fn(不被原子 replace 覆盖)。++ 须在进程内 ``asyncio.Lock`` 之内、经 ``to_thread`` 调用,避免阻塞事件循环。+ """+ self._path.parent.mkdir(parents=True, exist_ok=True)+ lock_path = self._path.with_suffix(self._path.suffix + ".lock")+ with portalocker.Lock(str(lock_path), timeout=self._file_lock_timeout):+ return fn()++ async def _run_locked(self, fn: Callable[[], _T]) -> _T:+ """同进程协程串行 + 跨进程文件锁;文件锁等待放到线程池,避免阻塞事件循环。"""+ async with self._lock:+ return await asyncio.to_thread(self._call_under_file_lock, fn)+async def list_jobs(self) -> list[CronJob]:# 惰性迁移:在同一个锁内 read + 推断缺 work_mode 的老 job + writeback,# 替代启动迁移 ``migrate_legacy_jobs_at_startup``。# 已迁移过的系统 jobs 全部 work_mode 合法,``needs_migration=False``# 直接跳过 lookup 与 writeback,零额外开销。- async with self._lock:+ def _body() -> list[CronJob]:data = self._read_json_unlocked()jobs_raw = data.get("jobs") or []if not isinstance(jobs_raw, list):@@ -176,6 +209,9 @@ class CronJobStore:except Exception:# Ignore invalid entries to keep system robustcontinue+ return jobs++ jobs = await self._run_locked(_body)jobs.sort(key=lambda j: (j.updated_at or 0.0, j.created_at or 0.0), reverse=True)return jobs@@ -372,7 +408,8 @@ class CronJobStore:raise _ProactiveJobProtected("主动推荐定时任务由设置→主动推荐开关控制,不能删除;请到设置关闭开关。")- async with self._lock:++ def _body() -> bool:data = self._read_json_unlocked()jobs_raw = data.get("jobs") or []if not isinstance(jobs_raw, list):@@ -392,8 +429,10 @@ class CronJobStore:self._write_json_unlocked(data)return deleted+ return await self._run_locked(_body)+async def _upsert_job(self, job: CronJob) -> None:- async with self._lock:+ def _body() -> None:data = self._read_json_unlocked()jobs_raw = data.get("jobs") or []if not isinstance(jobs_raw, list):@@ -414,9 +453,10 @@ class CronJobStore:data["jobs"] = outself._write_json_unlocked(data)+ await self._run_locked(_body)+async def _read_json(self) -> dict[str, Any]:- async with self._lock:- return self._read_json_unlocked()+ return await self._run_locked(self._read_json_unlocked)def _read_json_unlocked(self) -> dict[str, Any]:path = self._pathdiff --git a/tests/unit_tests/gateway/test_cron_scheduler.py b/tests/unit_tests/gateway/test_cron_scheduler.pyindex b477890ce2..95bd24c1fa 100644--- a/tests/unit_tests/gateway/test_cron_scheduler.py+++ b/tests/unit_tests/gateway/test_cron_scheduler.py@@ -1410,3 +1410,77 @@ class TestCronBroadcastText:text="[cron] 任务执行超时(>10min)",is_placeholder=False,) == "[cron] 任务执行超时(>10min)"++def _create_many_jobs_in_thread(path: Path, prefix: str, n: int) -> None:+ """在独立线程 + 独立事件循环里写 store(模拟另一 Gateway 进程)。"""+ store = CronJobStore(path=path)++ async def _run() -> None:+ for i in range(n):+ await store.create_job(+ name=f"{prefix}-{i}",+ cron_expr="0 0 9 * * ? *",+ timezone="Asia/Shanghai",+ description="reminder",+ targets="web",+ )++ asyncio.run(_run())+++class TestCronJobStoreFileLock:+ """验证 portalocker 伴生锁包住 read-modify-write,避免多实例 lost update。"""++ def test_threaded_concurrent_creates_preserve_all_jobs(self, tmp_path):+ """两线程各持独立 store 并发 create,最终 jobs 应全部保留。"""+ from concurrent.futures import ThreadPoolExecutor++ store_file = tmp_path / "cron_jobs.json"+ n = 40++ with ThreadPoolExecutor(max_workers=2) as pool:+ fut_a = pool.submit(_create_many_jobs_in_thread, store_file, "a", n)+ fut_b = pool.submit(_create_many_jobs_in_thread, store_file, "b", n)+ fut_a.result(timeout=120)+ fut_b.result(timeout=120)++ jobs = asyncio.run(CronJobStore(path=store_file).list_jobs())+ names = sorted(j.name for j in jobs)+ expected = sorted([f"a-{i}" for i in range(n)] + [f"b-{i}" for i in range(n)])+ assert len(jobs) == 2 * n, (+ f"lost update without effective file lock: got {len(jobs)}, expected {2 * n}"+ )+ assert names == expected+ assert store_file.with_suffix(".json.lock").exists()++ @pytest.mark.asyncio+ async def test_held_file_lock_times_out_other_store(self, tmp_path):+ """外部已持有伴生锁时,短超时的 store 写操作应抛 LockException。"""+ import portalocker++ store_file = tmp_path / "cron_jobs.json"+ lock_path = store_file.with_suffix(".json.lock")+ store = CronJobStore(path=store_file, file_lock_timeout=0.2)++ store_file.parent.mkdir(parents=True, exist_ok=True)+ with portalocker.Lock(str(lock_path), timeout=1.0):+ with pytest.raises(portalocker.exceptions.LockException):+ await store.create_job(+ name="blocked",+ cron_expr="0 0 9 * * ? *",+ timezone="Asia/Shanghai",+ description="reminder",+ targets="web",+ )++ # 锁释放后应可正常写入+ job = await store.create_job(+ name="after-unlock",+ cron_expr="0 0 9 * * ? *",+ timezone="Asia/Shanghai",+ description="reminder",+ targets="web",+ )+ assert job.name == "after-unlock"+ listed = await store.list_jobs()+ assert any(j.id == job.id for j in listed)