Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(bot): atomically persist cron store (#4733)

wutongyuonced3bdd5494e67
diff --git a/bot/vikingbot/cron/service.py b/bot/vikingbot/cron/service.py
index dcd6e8ccf..b23d4dc41 100644
--- a/bot/vikingbot/cron/service.py
+++ b/bot/vikingbot/cron/service.py
@@ -169,7 +169,12 @@ class CronService:
],
}
- self.store_path.write_text(json.dumps(data, indent=2))
+ temporary = self.store_path.with_name(f".{self.store_path.name}.{uuid.uuid4().hex}.tmp")
+ try:
+ temporary.write_text(json.dumps(data, indent=2))
+ temporary.replace(self.store_path)
+ finally:
+ temporary.unlink(missing_ok=True)
async def start(self) -> None:
"""Start the cron service."""
diff --git a/bot/vikingbot/tests/unit/test_cron_service.py b/bot/vikingbot/tests/unit/test_cron_service.py
new file mode 100644
index 000000000..08ba2c0f9
--- /dev/null
+++ b/bot/vikingbot/tests/unit/test_cron_service.py
@@ -0,0 +1,32 @@
+import json
+from pathlib import Path
+
+import pytest
+
+from vikingbot.cron.service import CronService
+from vikingbot.cron.types import CronJob, CronStore
+
+
+def _service(path: Path) -> CronService:
+ service = CronService(path)
+ service._store = CronStore(jobs=[CronJob(id="new", name="new")])
+ return service
+
+
+def test_save_store_keeps_existing_file_when_write_is_interrupted(tmp_path, monkeypatch):
+ path = tmp_path / "cron.json"
+ original_data = {"version": 1, "jobs": []}
+ path.write_text(json.dumps(original_data))
+ original_write_text = Path.write_text
+
+ def interrupted_write(self, data, *args, **kwargs):
+ original_write_text(self, data[:10], *args, **kwargs)
+ raise OSError("simulated interruption")
+
+ monkeypatch.setattr(Path, "write_text", interrupted_write)
+
+ with pytest.raises(OSError, match="simulated interruption"):
+ _service(path)._save_store()
+
+ assert json.loads(path.read_text()) == original_data
+ assert not list(tmp_path.glob(".cron.json.*.tmp"))