DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(knowledge): persist linked folder sync state updates
huy6ae7a68120b8
diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.pyindex 8b4d813d7..613030878 100644--- a/deeptutor/knowledge/manager.py+++ b/deeptutor/knowledge/manager.py@@ -15,6 +15,7 @@ from pathlib import Pathimport shutilimport statimport sys+import tempfilefrom typing import Anyfrom deeptutor.knowledge.kb_types import (@@ -257,6 +258,26 @@ def _reconcile_embedding_flags(knowledge_bases: dict, base_dir: Path | None = Noreturn changed+def _write_json_atomic(path: Path, payload: dict) -> None:+ """Write JSON via a same-directory temp file and ``os.replace`` so+ readers only ever see the previous or the new file, never a partial+ write, and a crash mid-write cannot leave ``path`` truncated.+ """+ fd, tmp_name = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.name}.", suffix=".tmp")+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as fp:+ json.dump(payload, fp, indent=2, ensure_ascii=False)+ fp.flush()+ os.fsync(fp.fileno())+ os.replace(tmp_name, path)+ except BaseException:+ try:+ os.unlink(tmp_name)+ except OSError:+ pass+ raise++class KnowledgeBaseManager:"""Manager for knowledge bases"""@@ -1667,6 +1688,7 @@ class KnowledgeBaseManager:folder["synced_files"] = file_statesfolder["file_count"] = len(file_states)+ _write_json_atomic(metadata_file, metadata)breakdiff --git a/tests/knowledge/test_linked_folder_sync.py b/tests/knowledge/test_linked_folder_sync.pynew file mode 100644index 000000000..b3c820cf0--- /dev/null+++ b/tests/knowledge/test_linked_folder_sync.py@@ -0,0 +1,72 @@+"""Persistence of linked-folder sync state (``metadata.json``).++``update_folder_sync_state()`` used to mutate the loaded metadata dict and+return without writing it back, so ``last_sync``/``synced_files`` silently+vanished while the API layer logged success. These tests pin the write-back+and the atomicity contract of the metadata writer.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from deeptutor.knowledge.manager import KnowledgeBaseManager, _write_json_atomic+++def _manager_with_linked_folder(tmp_path: Path) -> tuple[KnowledgeBaseManager, Path, str, Path]:+ """A registered KB with one linked folder containing one markdown file."""+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))++ kb_dir = manager.base_dir / "kb"+ kb_dir.mkdir()+ manager.register_knowledge_base("kb")++ source = tmp_path / "notes"+ source.mkdir()+ doc = source / "note.md"+ doc.write_text("hello", encoding="utf-8")++ folder_info = manager.link_folder("kb", str(source))+ return manager, kb_dir / "metadata.json", folder_info["id"], doc+++def test_update_folder_sync_state_persists_to_disk(tmp_path: Path) -> None:+ manager, metadata_file, folder_id, doc = _manager_with_linked_folder(tmp_path)++ manager.update_folder_sync_state("kb", folder_id, [str(doc)])++ on_disk = json.loads(metadata_file.read_text(encoding="utf-8"))+ folder = on_disk["linked_folders"][0]+ assert "last_sync" in folder+ assert str(doc) in folder["synced_files"]+ assert folder["file_count"] == 1++ # A fresh manager (new process in real life) must see the sync state too.+ reloaded = KnowledgeBaseManager(base_dir=str(manager.base_dir))+ folder = reloaded.get_linked_folders("kb")[0]+ assert "last_sync" in folder+ assert str(doc) in folder["synced_files"]+++def test_update_folder_sync_state_unknown_folder_writes_nothing(tmp_path: Path) -> None:+ manager, metadata_file, _folder_id, doc = _manager_with_linked_folder(tmp_path)+ before = metadata_file.read_bytes()++ manager.update_folder_sync_state("kb", "no-such-id", [str(doc)])++ assert metadata_file.read_bytes() == before+++def test_write_json_atomic_preserves_original_on_failure(tmp_path: Path) -> None:+ target = tmp_path / "metadata.json"+ target.write_text('{"ok": true}', encoding="utf-8")++ with pytest.raises(TypeError):+ _write_json_atomic(target, {"bad": object()})++ assert json.loads(target.read_text(encoding="utf-8")) == {"ok": True}+ # The failed write must not litter temp files next to the target.+ assert [p.name for p in tmp_path.iterdir()] == ["metadata.json"]