From 0c8593bf00469e2d743990f1c169d2fc8dfb6fdd Mon Sep 17 00:00:00 2001 From: RRFZ <247457381+Plastic-time@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:22:25 -0400 Subject: [PATCH] fix(knowledge): stop Windows readers from wiping kb_config.json On Windows, file_lock_shared took msvcrt LK_NBLCK, which is an exclusive, mandatory byte-range lock (msvcrt has no shared lock). A reader that overlapped another reader failed with PermissionError, _read_and_reconcile_config mapped that to an empty catalog, and the next update_kb_status auto-registered its KB into the empty catalog and saved it, dropping every other knowledge base's entry from kb_config.json. Writers already replace the file atomically, so readers need no lock: take none on Windows. POSIX keeps its LOCK_SH. --- deeptutor/knowledge/manager.py | 13 ++- .../test_manager_concurrent_reads.py | 80 +++++++++++++++++++ 2 files changed, 85 insertions(+), 8 deletions(-) create mode 100644 tests/knowledge/test_manager_concurrent_reads.py diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py index 39241853d..19b94b899 100644 --- a/deeptutor/knowledge/manager.py +++ b/deeptutor/knowledge/manager.py @@ -129,14 +129,11 @@ def _detect_provider_from_versions(versions: list[dict[str, Any]]) -> str: def file_lock_shared(file_handle): """Acquire a shared (read) 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) + # msvcrt has no shared lock: LK_NBLCK is exclusive and mandatory, so a + # second concurrent reader failed at once, read the catalog as empty, + # and the next status update saved that over kb_config.json. Writers + # replace the file atomically, so a reader needs no lock here. + yield else: import fcntl diff --git a/tests/knowledge/test_manager_concurrent_reads.py b/tests/knowledge/test_manager_concurrent_reads.py new file mode 100644 index 000000000..5725f1dad --- /dev/null +++ b/tests/knowledge/test_manager_concurrent_reads.py @@ -0,0 +1,80 @@ +"""Concurrent readers of ``kb_config.json`` must never see, or save, an empty catalog. + +``msvcrt`` has no shared lock: the Windows branch of ``file_lock_shared`` took +an exclusive, mandatory byte-range lock, so a reader that overlapped another +one failed, ``_read_and_reconcile_config`` returned ``{"knowledge_bases": {}}``, +and the next ``update_kb_status`` re-registered its own KB into that empty +catalog and saved it over every other entry. +""" + +from __future__ import annotations + +import json +from pathlib import Path +import sys +import threading +from types import SimpleNamespace + +import deeptutor.knowledge.manager as manager_module +from deeptutor.knowledge.manager import KnowledgeBaseManager + + +def _seed(tmp_path: Path) -> Path: + config = { + "knowledge_bases": { + name: {"path": name, "description": f"notes for {name}", "status": "ready"} + for name in ("kb0", "kb1", "kb2") + } + } + for name in config["knowledge_bases"]: + (tmp_path / name).mkdir() + config_file = tmp_path / "kb_config.json" + config_file.write_text(json.dumps(config), encoding="utf-8") + return config_file + + +def test_windows_reader_does_not_take_an_exclusive_lock(tmp_path, monkeypatch) -> None: + config_file = _seed(tmp_path) + + def held_by_another_reader(*_args): + raise PermissionError(13, "Permission denied") + + monkeypatch.setattr(manager_module, "sys", SimpleNamespace(platform="win32")) + monkeypatch.setitem( + sys.modules, + "msvcrt", + SimpleNamespace(LK_NBLCK=2, LK_UNLCK=0, locking=held_by_another_reader), + ) + + # Every read below overlaps another reader's byte-range lock. + manager = KnowledgeBaseManager(base_dir=str(tmp_path)) + manager.update_kb_status(name="kb0", status="processing") + + saved = json.loads(config_file.read_text(encoding="utf-8"))["knowledge_bases"] + assert sorted(saved) == ["kb0", "kb1", "kb2"] + assert saved["kb1"]["description"] == "notes for kb1" + + +def test_status_updates_racing_readers_keep_the_catalog(tmp_path) -> None: + config_file = _seed(tmp_path) + stop = threading.Event() + + def read_until_stopped() -> None: + reader = KnowledgeBaseManager(base_dir=str(tmp_path)) + while not stop.is_set(): + reader._read_and_reconcile_config() + + readers = [threading.Thread(target=read_until_stopped) for _ in range(6)] + for thread in readers: + thread.start() + try: + writer = KnowledgeBaseManager(base_dir=str(tmp_path)) + for _ in range(200): + writer.update_kb_status(name="kb0", status="ready") + finally: + stop.set() + for thread in readers: + thread.join() + + saved = json.loads(config_file.read_text(encoding="utf-8"))["knowledge_bases"] + assert sorted(saved) == ["kb0", "kb1", "kb2"]