Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

refactor(knowledge): unify all manager JSON writes on services.file_io atomic writer

Bingxi Zhao (Frank)96a3b5db6bb6
diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py
index 613030878..d212e1db0 100644
--- a/deeptutor/knowledge/manager.py
+++ b/deeptutor/knowledge/manager.py
@@ -15,7 +15,6 @@ from pathlib import Path
import shutil
import stat
import sys
-import tempfile
from typing import Any
from deeptutor.knowledge.kb_types import (
@@ -26,6 +25,7 @@ from deeptutor.knowledge.kb_types import (
external_root_of,
is_connected_kb,
)
+from deeptutor.services.file_io import atomic_write_json
from deeptutor.services.rag.factory import (
DEFAULT_PROVIDER,
KNOWN_PROVIDERS,
@@ -86,7 +86,9 @@ def _detect_provider_from_versions(versions: list[dict[str, Any]]) -> str:
return DEFAULT_PROVIDER
-# Cross-platform file locking
+# Cross-platform file locking. Writers no longer take locks — every JSON
+# write in this module goes through ``atomic_write_json`` (temp file +
+# ``os.replace``), so readers always see a complete previous or new file.
@contextmanager
def file_lock_shared(file_handle):
"""Acquire a shared (read) lock on a file - cross-platform."""
@@ -109,28 +111,6 @@ def file_lock_shared(file_handle):
fcntl.flock(file_handle.fileno(), fcntl.LOCK_UN)
-@contextmanager
-def file_lock_exclusive(file_handle):
- """Acquire an exclusive (write) lock on a file - cross-platform."""
- if sys.platform == "win32":
- import msvcrt
-
- msvcrt.locking(file_handle.fileno(), msvcrt.LK_NBLCK, 1)
- try:
- yield
- finally:
- file_handle.seek(0)
- msvcrt.locking(file_handle.fileno(), msvcrt.LK_UNLCK, 1)
- else:
- import fcntl
-
- fcntl.flock(file_handle.fileno(), fcntl.LOCK_EX)
- try:
- yield
- finally:
- fcntl.flock(file_handle.fileno(), fcntl.LOCK_UN)
-
-
def _get_embedding_fingerprint() -> tuple[str, int] | None:
"""Return ``(model_name, dimension)`` of the active embedding config."""
try:
@@ -258,26 +238,6 @@ def _reconcile_embedding_flags(knowledge_bases: dict, base_dir: Path | None = No
return 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"""
@@ -367,11 +327,7 @@ class KnowledgeBaseManager:
if config_changed:
try:
- with open(self.config_file, "w", encoding="utf-8") as f:
- with file_lock_exclusive(f):
- json.dump(config, f, indent=2, ensure_ascii=False)
- f.flush()
- os.fsync(f.fileno())
+ atomic_write_json(self.config_file, config)
except Exception as save_err:
logger.warning(f"Failed to persist normalized KB config: {save_err}")
@@ -382,13 +338,13 @@ class KnowledgeBaseManager:
return {"knowledge_bases": {}}
def _save_config(self):
- """Save knowledge base configuration (thread-safe with file locking)"""
- # Use exclusive lock for writing
- with open(self.config_file, "w", encoding="utf-8") as f:
- with file_lock_exclusive(f):
- json.dump(self.config, f, indent=2, ensure_ascii=False)
- f.flush()
- os.fsync(f.fileno()) # Ensure data is written to disk
+ """Save knowledge base configuration.
+
+ Written via temp-file + ``os.replace`` so concurrent readers only
+ ever see the previous or the new file — ``open(..., "w")`` used to
+ truncate the config before the lock was even acquired.
+ """
+ atomic_write_json(self.config_file, self.config)
def _sync_kb_to_pb(self, name: str, kb_entry: dict) -> None:
"""
@@ -1483,9 +1439,7 @@ class KnowledgeBaseManager:
}
metadata["linked_folders"].append(folder_info)
- # Save metadata
- with open(metadata_file, "w", encoding="utf-8") as fp:
- json.dump(metadata, fp, indent=2, ensure_ascii=False)
+ atomic_write_json(metadata_file, metadata)
return folder_info
@@ -1549,8 +1503,7 @@ class KnowledgeBaseManager:
metadata["linked_folders"] = new_linked
- with open(metadata_file, "w", encoding="utf-8") as f:
- json.dump(metadata, f, indent=2, ensure_ascii=False)
+ atomic_write_json(metadata_file, metadata)
return True
@@ -1688,7 +1641,7 @@ class KnowledgeBaseManager:
folder["synced_files"] = file_states
folder["file_count"] = len(file_states)
- _write_json_atomic(metadata_file, metadata)
+ atomic_write_json(metadata_file, metadata)
break
diff --git a/deeptutor/services/file_io.py b/deeptutor/services/file_io.py
index b895914d6..13018c7c7 100644
--- a/deeptutor/services/file_io.py
+++ b/deeptutor/services/file_io.py
@@ -24,6 +24,11 @@ def atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
temporary_path = Path(handle.name)
json.dump(payload, handle, indent=2, ensure_ascii=False)
handle.write("\n")
+ handle.flush()
+ try:
+ os.fsync(handle.fileno())
+ except OSError:
+ pass
temporary_path.replace(path)
finally:
if temporary_path is not None:
diff --git a/tests/knowledge/test_linked_folder_sync.py b/tests/knowledge/test_linked_folder_sync.py
index b3c820cf0..a4e8ed353 100644
--- a/tests/knowledge/test_linked_folder_sync.py
+++ b/tests/knowledge/test_linked_folder_sync.py
@@ -2,8 +2,9 @@
``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.
+vanished while the API layer logged success. These tests pin the write-back.
+The atomicity contract of the shared writer lives in
+``tests/services/test_file_io.py``.
"""
from __future__ import annotations
@@ -11,9 +12,7 @@ from __future__ import annotations
import json
from pathlib import Path
-import pytest
-
-from deeptutor.knowledge.manager import KnowledgeBaseManager, _write_json_atomic
+from deeptutor.knowledge.manager import KnowledgeBaseManager
def _manager_with_linked_folder(tmp_path: Path) -> tuple[KnowledgeBaseManager, Path, str, Path]:
@@ -58,15 +57,3 @@ def test_update_folder_sync_state_unknown_folder_writes_nothing(tmp_path: Path)
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"]
diff --git a/tests/services/test_file_io.py b/tests/services/test_file_io.py
index 1163419db..2c4107830 100644
--- a/tests/services/test_file_io.py
+++ b/tests/services/test_file_io.py
@@ -39,6 +39,18 @@ def test_atomic_write_json_cleans_up_temporary_file_on_failure(
assert list(path.parent.iterdir()) == []
+def test_atomic_write_json_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):
+ atomic_write_json(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"]
+
+
def test_atomic_write_text_creates_parent_and_replaces_content(tmp_path: Path) -> None:
path = tmp_path / "nested" / "note.md"