Skip to content

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

fix(settings): preserve catalog after failed file reads

dajiaohuang593233431459
diff --git a/deeptutor/services/config/model_catalog.py b/deeptutor/services/config/model_catalog.py
index dfc0831ee..30bda72a2 100644
--- a/deeptutor/services/config/model_catalog.py
+++ b/deeptutor/services/config/model_catalog.py
@@ -289,7 +289,7 @@ class ModelCatalogService:
return {}
try:
loaded = json.loads(self.path.read_text(encoding="utf-8"))
- except Exception:
+ except (json.JSONDecodeError, UnicodeDecodeError):
return {}
return loaded if isinstance(loaded, dict) else {}
diff --git a/tests/services/test_model_catalog.py b/tests/services/test_model_catalog.py
index 7f2911a63..911c50bf3 100644
--- a/tests/services/test_model_catalog.py
+++ b/tests/services/test_model_catalog.py
@@ -1,6 +1,9 @@
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
+from typing import Any
+
+import pytest
from deeptutor.services.config.model_catalog import SERVICE_NAMES, ModelCatalogService
@@ -113,6 +116,37 @@ def test_load_recovers_invalid_catalog_with_defaults(tmp_path: Path):
assert set(saved["services"]) == expected_services
[email protected]("operation", ["load", "update", "apply"])
[email protected]("error_type", [OSError, PermissionError])
+def test_catalog_read_error_preserves_existing_file(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ operation: str,
+ error_type: type[OSError],
+) -> None:
+ """An unreadable catalog must not be replaced by an empty catalog."""
+ catalog_path = tmp_path / "model_catalog.json"
+ original = b'{"version": 1, "services": {}, "saved_selection": "retain-me"}'
+ catalog_path.write_bytes(original)
+ read_text = Path.read_text
+
+ def fail_catalog_read(path: Path, *args: Any, **kwargs: Any) -> str:
+ """Fail only the source read while leaving the actual writer usable."""
+ if path == catalog_path:
+ raise error_type("catalog temporarily unreadable")
+ return read_text(path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "read_text", fail_catalog_read)
+ service = ModelCatalogService(path=catalog_path)
+ with pytest.raises(error_type, match="catalog temporarily unreadable"):
+ if operation == "update":
+ service.update(lambda catalog: catalog.update({"new_setting": True}))
+ else:
+ getattr(service, operation)()
+
+ assert catalog_path.read_bytes() == original
+
+
def test_load_migrates_only_legacy_dashscope_stt_model(tmp_path: Path):
catalog_path = tmp_path / "model_catalog.json"
catalog_path.write_text(