Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(journal_quality): promote downloaded snapshots with os.replace so Windows refreshes work (#7196)

EnragedAntelope6c0e0bd84663
diff --git a/changelog.d/7195.bugfix.md b/changelog.d/7195.bugfix.md
new file mode 100644
index 0000000000..fdb44681d2
--- /dev/null
+++ b/changelog.d/7195.bugfix.md
@@ -0,0 +1 @@
+Promote the journal-quality data files with `os.replace` instead of `Path.rename`, so refreshing already-installed data works on Windows instead of failing with `FileExistsError` for every source.
diff --git a/src/local_deep_research/journal_quality/data_sources/base.py b/src/local_deep_research/journal_quality/data_sources/base.py
index d7d8c3f5ce..af0ae7c256 100644
--- a/src/local_deep_research/journal_quality/data_sources/base.py
+++ b/src/local_deep_research/journal_quality/data_sources/base.py
@@ -10,6 +10,7 @@ lazy-load auto-download path in `JournalDataManager`.
from __future__ import annotations
+import os
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any
@@ -17,6 +18,20 @@ from typing import Any
from loguru import logger
+def atomic_replace(tmp: Path, output: Path) -> None:
+ """Move a fully-written temp file onto ``output``, overwriting it.
+
+ Uses ``os.replace`` rather than ``Path.rename``: on Windows ``rename``
+ raises ``FileExistsError`` if the destination already exists, which is
+ the normal case when refreshing data that was downloaded before (POSIX
+ ``rename`` overwrites silently, so the bug is invisible on Linux/macOS).
+ ``os.replace`` overwrites the destination on both platforms and is atomic
+ on POSIX (Windows can refuse it while a reader holds the file open - the
+ same caveat tracked for the journal-quality DB in #6135).
+ """
+ os.replace(tmp, output)
+
+
class DataSource(ABC):
"""Abstract base class for one downloadable academic data source.
diff --git a/src/local_deep_research/journal_quality/data_sources/doaj.py b/src/local_deep_research/journal_quality/data_sources/doaj.py
index a148221687..097d3595b1 100644
--- a/src/local_deep_research/journal_quality/data_sources/doaj.py
+++ b/src/local_deep_research/journal_quality/data_sources/doaj.py
@@ -18,7 +18,7 @@ from pathlib import Path
from loguru import logger
from ...utilities.citation_normalizer import normalize_issn
-from .base import DataSource
+from .base import DataSource, atomic_replace
# Public CSV of the full DOAJ journal list. CC0 metadata.
_DOAJ_CSV_URL = "https://doaj.org/csv"
@@ -110,7 +110,7 @@ class DOAJSource(DataSource):
tmp = data_dir / f"{self.filename}.tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump({"journals": journals}, f)
- tmp.rename(output)
+ atomic_replace(tmp, output)
elapsed = time.time() - start
logger.info(f"DOAJ: saved {len(journals):,} journals in {elapsed:.0f}s")
diff --git a/src/local_deep_research/journal_quality/data_sources/institutions.py b/src/local_deep_research/journal_quality/data_sources/institutions.py
index 59a2208691..746cc8107d 100644
--- a/src/local_deep_research/journal_quality/data_sources/institutions.py
+++ b/src/local_deep_research/journal_quality/data_sources/institutions.py
@@ -32,7 +32,7 @@ from ._openalex_common import (
validate_manifest_entries,
)
from ..scoring import normalize_name
-from .base import DataSource
+from .base import DataSource, atomic_replace
_OPENALEX_INSTITUTIONS_MANIFEST = (
f"{OPENALEX_S3_BASE}/data/jsonl/institutions/manifest.json"
@@ -193,7 +193,7 @@ class InstitutionSource(DataSource):
tmp = data_dir / f"{self.filename}.tmp"
with gzip.open(tmp, "wt", encoding="utf-8") as f:
json.dump(payload, f)
- tmp.rename(output)
+ atomic_replace(tmp, output)
elapsed = time.time() - start
logger.info(
diff --git a/src/local_deep_research/journal_quality/data_sources/jabref.py b/src/local_deep_research/journal_quality/data_sources/jabref.py
index 58c28bf731..e20819c481 100644
--- a/src/local_deep_research/journal_quality/data_sources/jabref.py
+++ b/src/local_deep_research/journal_quality/data_sources/jabref.py
@@ -14,7 +14,7 @@ from pathlib import Path
from loguru import logger
-from .base import DataSource
+from .base import DataSource, atomic_replace
_JABREF_BASE = (
"https://raw.githubusercontent.com/JabRef/abbrv.jabref.org/main/journals"
@@ -129,7 +129,7 @@ class JabRefSource(DataSource):
tmp = data_dir / f"{self.filename}.tmp"
with gzip.open(tmp, "wt", encoding="utf-8") as f:
json.dump({"abbrev_to_full": abbrev_to_full}, f)
- tmp.rename(output)
+ atomic_replace(tmp, output)
logger.info(
f"JabRef: saved {len(abbrev_to_full)} abbreviation mappings"
diff --git a/src/local_deep_research/journal_quality/data_sources/openalex.py b/src/local_deep_research/journal_quality/data_sources/openalex.py
index 98ba5d0151..e974aac061 100644
--- a/src/local_deep_research/journal_quality/data_sources/openalex.py
+++ b/src/local_deep_research/journal_quality/data_sources/openalex.py
@@ -31,7 +31,7 @@ from pathlib import Path
from loguru import logger
from ...utilities.citation_normalizer import normalize_issn
-from .base import DataSource
+from .base import DataSource, atomic_replace
from ._openalex_common import (
OPENALEX_S3_BASE,
@@ -258,7 +258,7 @@ class OpenAlexSource(DataSource):
tmp = data_dir / f"{self.filename}.tmp"
with gzip.open(tmp, "wt", encoding="utf-8") as f:
json.dump({"s": sources}, f)
- tmp.rename(output)
+ atomic_replace(tmp, output)
elapsed = time.time() - start
logger.info(
diff --git a/src/local_deep_research/journal_quality/data_sources/predatory.py b/src/local_deep_research/journal_quality/data_sources/predatory.py
index 58da5b54f3..f87e908f91 100644
--- a/src/local_deep_research/journal_quality/data_sources/predatory.py
+++ b/src/local_deep_research/journal_quality/data_sources/predatory.py
@@ -15,7 +15,7 @@ from pathlib import Path
from loguru import logger
-from .base import DataSource
+from .base import DataSource, atomic_replace
_PREDATORY_BASE = (
"https://raw.githubusercontent.com/stop-predatory-journals/"
@@ -134,7 +134,7 @@ class PredatorySource(DataSource):
tmp = data_dir / f"{self.filename}.tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(payload, f)
- tmp.rename(output)
+ atomic_replace(tmp, output)
logger.info(
f"Predatory: saved {len(publishers)} publishers + "
diff --git a/tests/journal_quality/test_refresh_replaces_installed_file.py b/tests/journal_quality/test_refresh_replaces_installed_file.py
new file mode 100644
index 0000000000..e2d722caf4
--- /dev/null
+++ b/tests/journal_quality/test_refresh_replaces_installed_file.py
@@ -0,0 +1,122 @@
+"""Journal-data refreshes must replace an already-installed snapshot.
+
+`Path.rename` is `os.rename`, which on Windows raises `FileExistsError` when
+the destination exists - the normal case when refreshing data that was
+downloaded before. POSIX `rename` overwrites silently, so Linux/macOS CI never
+saw the failure, but on Windows every source aborted at the promotion step
+(`✗ ... FileExistsError` on `/metrics/journals`) and the update could never
+complete.
+
+`windows_rename` below gives `os.rename` that Windows behaviour, so these tests
+pin the promotion to an overwriting primitive (`os.replace`) rather than to
+whatever `os.rename` happens to do on the host.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.journal_quality import data_sources as data_sources_pkg
+from local_deep_research.journal_quality.data_sources import (
+ predatory as pred_mod,
+)
+from local_deep_research.journal_quality.data_sources.base import (
+ atomic_replace,
+)
+from local_deep_research.journal_quality.data_sources.predatory import (
+ PredatorySource,
+)
+
+
+def windows_rename(monkeypatch):
+ real_rename = os.rename
+
+ def _rename(src, dst, *args, **kwargs):
+ if Path(dst).exists():
+ raise FileExistsError(17, "File exists", str(dst))
+ return real_rename(src, dst, *args, **kwargs)
+
+ monkeypatch.setattr(os, "rename", _rename)
+
+
+def _csv_response(text: str) -> MagicMock:
+ resp = MagicMock()
+ resp.raise_for_status = MagicMock()
+ resp.text = text
+ return resp
+
+
+def test_atomic_replace_overwrites_existing_destination(
+ tmp_path, windows_rename
+):
+ """The destination is replaced even where rename would refuse."""
+ tmp = tmp_path / "snapshot.json.tmp"
+ output = tmp_path / "snapshot.json"
+ tmp.write_bytes(b'{"version": "new"}')
+ output.write_bytes(b'{"version": "installed"}')
+
+ atomic_replace(tmp, output)
+
+ assert json.loads(output.read_text(encoding="utf-8"))["version"] == "new"
+ assert not tmp.exists()
+
+
+def test_predatory_refresh_replaces_installed_snapshot(
+ tmp_path, monkeypatch, windows_rename
+):
+ """A fetch over an existing predatory.json must overwrite it."""
+ monkeypatch.setattr(pred_mod, "_MIN_PREDATORY_TOTAL", 5)
+
+ installed = tmp_path / "predatory.json"
+ installed.write_bytes(b'{"sentinel": "previous build"}')
+
+ publishers_csv = "name,url\n" + "\n".join(
+ f"Pub {i},http://p{i}.example" for i in range(10)
+ )
+
+ with patch(
+ "local_deep_research.security.safe_requests.safe_get_with_retries",
+ ) as mock_get:
+ mock_get.side_effect = [
+ _csv_response(publishers_csv),
+ _csv_response("name,url\n"),
+ _csv_response("hijacked,hijackedurl,authentic,authenticurl\n"),
+ ]
+ result = PredatorySource().fetch(tmp_path)
+
+ assert result == 10
+ assert (
+ json.loads(installed.read_text(encoding="utf-8"))["metadata"][
+ "publisher_count"
+ ]
+ == 10
+ )
+ assert not (tmp_path / "predatory.json.tmp").exists()
+
+
+def test_every_source_promotes_through_atomic_replace():
+ """No source may regress to ``tmp.rename`` (Windows-refusing) promotion.
+
+ Only the predatory call site is exercised behaviourally above; the other
+ four share the same bug but cannot be reached from a Linux CI host (POSIX
+ ``rename`` overwrites silently), so pin the whole set structurally here.
+ """
+ sources_dir = Path(data_sources_pkg.__file__).parent
+ modules = sorted(sources_dir.glob("*.py"))
+
+ offenders = [
+ p.name for p in modules if ".rename(" in p.read_text(encoding="utf-8")
+ ]
+ assert offenders == [], f"use atomic_replace, not rename: {offenders}"
+
+ for name in ("doaj", "institutions", "jabref", "openalex", "predatory"):
+ source = (sources_dir / f"{name}.py").read_text(encoding="utf-8")
+ assert "atomic_replace(" in source, (
+ f"{name}.py must promote its snapshot via atomic_replace"
+ )