~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): gate the journal-data lazy build on the active egress scope (#6434)
LearningCircuitde31bc0e987a
diff --git a/changelog.d/6434.security.md b/changelog.d/6434.security.mdnew file mode 100644index 0000000000..dc8f19d270--- /dev/null+++ b/changelog.d/6434.security.md@@ -0,0 +1 @@+The journal-data lazy build now honours the user's egress scope. When the reputation database file is missing or fails its schema/corruption check, a read through it could trigger the full public dataset download from OpenAlex/DOAJ/GitHub — synchronously inside a research run whose PRIVATE_ONLY/STRICT scope forbids public egress, or from a plain journal-dashboard page load. The dashboard download button and the filter's background fetch already refused under those scopes, but the lazy-build path decided on test mock mode alone. It now refuses the network download under a forbidding active egress context, with a `policy_audit` log line and a scope-specific error, and the dashboard's journal read endpoints — which run on request threads where no egress context is armed — resolve the egress scope a research run for that user would get — the stored scope, with the default adaptive scope resolved against the user's primary search engine exactly as the research worker and the reputation filter resolve it, so a private primary (library, collection or private retriever) counts as private-only, and an unresolvable scope or missing primary fails closed — and answer "reference database unavailable" in the one case where a read would otherwise have to download: the downloaded snapshots are absent and the compiled database is missing or unusable. Purely local builds from already-present snapshots still proceed everywhere, the read endpoints included, and an existing, valid database is read as before under every scope. A refused build no longer poisons the shared 30-second availability cache for other callers, and the dashboard's per-research responses now carry a `reference_data_available` flag, true only when the reference database was actually opened for the lookups, so a reference database that was withheld by the egress scope or failed to build or open reads as "not checked" rather than "no predatory journals found". The dashboard's data-status endpoint now applies that same usability check to the compiled database: a file that exists but fails it is reported as unavailable rather than present, so the install banner and download prompt appear instead of a dashboard that quietly renders zeros. Every SQLite URI the journal-quality module opens — the read-only validity probe, the runtime read-only engine and the build's post-build count — now goes through one helper that uses an empty authority and a fully percent-encoded path built from the path's filesystem bytes, so data-directory names containing `?`, `#`, `%`, spaces or (on Linux/macOS) bytes that are not valid UTF-8 open correctly, and a Windows UNC path is no longer turned into a URI authority that SQLite refuses; and an existing database that cannot be opened at all is now left in place and reported unavailable instead of being deleted as corrupt.diff --git a/src/local_deep_research/journal_quality/data_sources/openalex.py b/src/local_deep_research/journal_quality/data_sources/openalex.pyindex 386b192776..98ba5d0151 100644--- a/src/local_deep_research/journal_quality/data_sources/openalex.py+++ b/src/local_deep_research/journal_quality/data_sources/openalex.py@@ -69,6 +69,11 @@ class OpenAlexSource(DataSource):"~280K journals and conferences with h-index, impact factor, ""and publisher metadata")+ # Deliberately NOT `downloader.REQUIRED_SNAPSHOT_FILENAME`: downloader.py+ # imports this package (`from .data_sources import ALL_SOURCES,+ # get_source`) before it defines that constant, and this is a class+ # attribute (evaluated at class-definition / import time, not inside a+ # function body), so even a lazy import wouldn't avoid the cycle.filename = "openalex_sources.json.gz"count_label = "OpenAlex sources"auto_download = False # large; user opts in via dashboarddiff --git a/src/local_deep_research/journal_quality/db.py b/src/local_deep_research/journal_quality/db.pyindex e2654c36ef..f0c0f642d1 100644--- a/src/local_deep_research/journal_quality/db.py+++ b/src/local_deep_research/journal_quality/db.py@@ -33,8 +33,9 @@ import sysimport threadingimport timefrom contextlib import closing, contextmanager-from pathlib import Path+from pathlib import Path, PurePathfrom typing import Iterable, Iterator, Optional+from urllib.parse import quotefrom loguru import loggerfrom sqlalchemy import create_engine, func, inspect, or_, select@@ -102,6 +103,148 @@ _SORT_COLUMNS = frozenset(_MAX_SEARCH_LEN = 100+def sqlite_readonly_uri(path: PurePath, *, immutable: bool = False) -> str:+ """Build a ``mode=ro`` SQLite URI for an absolute ``path``.++ With ``immutable=True`` the query string is ``mode=ro&immutable=1``+ (the runtime engine's flags). Every SQLite URI this package opens+ goes through this one helper so that no call site interpolates a raw+ path into a ``file:`` URI.++ The URI always has an EMPTY authority (``file://`` + path), because+ SQLite rejects any authority other than empty or ``localhost`` with+ "invalid uri authority" unless it was compiled with+ ``SQLITE_ALLOW_URI_AUTHORITY`` — which the stock builds are not.+ ``Path.as_uri()`` is therefore unusable here: for a Windows UNC path+ (``\\\\server\\share\\...``, and a mapped drive that ``resolve()``+ turns into one) it yields ``file://server/share/...``, which SQLite+ refuses to open at all. The UNC host goes into the PATH instead —+ ``file:////server/share/...`` — which SQLite decodes to+ ``//server/share/...``, a path Windows opens as UNC. A drive path+ ``C:/...`` becomes ``file:///C:/...``, SQLite's documented Windows+ form, and a POSIX path ``/a/b`` becomes ``file:///a/b``.++ The path is percent-encoded with only ``/`` and ``:`` left literal,+ so ``?``, ``#``, ``%``, spaces and non-ASCII characters all+ round-trip through SQLite's URI decoder. What gets encoded is the+ path's filesystem BYTES (``os.fsencode``), not its ``str`` form: on+ POSIX a directory name that is not valid UTF-8 decodes to lone+ surrogates (``b"\\xe9"`` -> ``"\\udce9"``), which ``quote(str)``+ refuses with ``UnicodeEncodeError``; percent-encoding the bytes makes+ SQLite open exactly the on-disk name, as a plain+ ``sqlite3.connect(str_path)`` does. On Windows ``os.fsencode`` is+ UTF-8, the same bytes ``quote(str)`` would produce.++ Interpolating the raw path into ``f"file:{path}?mode=ro"`` instead+ lets a literal ``?`` or ``#`` in a data-directory name truncate the+ URI before ``?mode=ro`` — silently dropping the read-only flag and,+ on a database that does not otherwise exist at the truncated path,+ creating a stray 0-byte file there.++ Takes a ``PurePath`` so the Windows forms are unit-testable on any+ OS via ``PureWindowsPath``; the caller resolves the path first.+ """+ posix = PurePath(path).as_posix()+ if not posix.startswith("/"):+ # Windows drive path "C:/x" -> "/C:/x". A UNC path's as_posix()+ # already starts with "//server/share", giving four slashes.+ posix = "/" + posix+ query = "mode=ro&immutable=1" if immutable else "mode=ro"+ return "file://" + quote(os.fsencode(posix), safe=b"/:") + "?" + query+++#: ``journal_db_file_status`` results.+JOURNAL_DB_VALID = "valid"+JOURNAL_DB_INVALID = "invalid"+JOURNAL_DB_UNOPENABLE = "unopenable"+++def journal_db_file_status(path: Path) -> str:+ """Classify ``path`` as a compiled journal-quality DB, read-only.++ Returns one of:++ - ``JOURNAL_DB_VALID`` — the file opened and is usable as-is.+ - ``JOURNAL_DB_INVALID`` — the file is missing, or it OPENED but is+ not usable: a non-zero ``PRAGMA user_version`` that does not match+ the current schema (a real drift signal), or content SQLite+ rejects as a database (corruption). Rebuilding is the right fix.+ - ``JOURNAL_DB_UNOPENABLE`` — the file exists but the read-only open+ itself failed (permissions, a URI or path form this SQLite build+ refuses, an unreachable share). Nothing is known about the file's+ contents, so callers must NOT treat it as corrupt: deleting it on+ this signal would destroy a possibly-valid DB over an environment+ problem.++ A version of 0 means the file was built before schema stamping+ existed and is grandfathered in — we don't force a rebuild just+ because the stamp is missing.++ Side-effect-free on the target file, deliberately: it opens with the+ SQLite URI flag ``mode=ro`` (see ``sqlite_readonly_uri``), which+ never creates the target path, reads ``PRAGMA user_version``,+ touches ``sqlite_master`` to confirm the file really is a database,+ and closes the connection. It removes nothing and builds nothing.+ The one caveat is SQLite's own: opening a WAL-mode database — even+ read-only — can still create that database's ``-wal``/``-shm`` side+ files, since materializing them is how SQLite reads a WAL database+ at all.++ That is what makes it safe to call from a read path that only needs+ to know whether a read WOULD trigger a rebuild — see+ ``web/routers/metrics.py``'s ``_journal_ref_db_read_would_download``.+ ``JournalQualityDB._validate_existing_db`` wraps it with the+ destructive half (unlinking an INVALID file), which a read route+ must not do.+ """+ from ..utilities.resource_utils import safe_close++ try:+ resolved = Path(path).resolve()+ uri = sqlite_readonly_uri(resolved)+ conn = sqlite3.connect(uri, uri=True)+ except (sqlite3.DatabaseError, OSError, ValueError):+ if not Path(path).exists():+ # Nothing to protect — a missing file is simply "not a+ # usable DB", and a build creating it destroys nothing.+ return JOURNAL_DB_INVALID+ logger.exception(+ f"journal_quality.db at {path} exists but could not be "+ f"opened read-only"+ )+ return JOURNAL_DB_UNOPENABLE++ status = JOURNAL_DB_INVALID+ try:+ version = conn.execute("PRAGMA user_version").fetchone()[0]+ if version != 0 and version != JOURNAL_QUALITY_SCHEMA_VERSION:+ logger.warning(+ f"journal_quality.db schema_version={version}, "+ f"expected {JOURNAL_QUALITY_SCHEMA_VERSION} — "+ f"a rebuild is needed"+ )+ else:+ # Cheap sanity check — confirms the file is a valid DB.+ conn.execute("SELECT 1 FROM sqlite_master LIMIT 1").fetchone()+ status = JOURNAL_DB_VALID+ except (sqlite3.DatabaseError, OSError):+ logger.exception(f"journal_quality.db at {path} is unusable")+ finally:+ safe_close(conn, "journal_quality validate")+ return status+++def journal_db_file_is_valid(path: Path) -> bool:+ """Return True if ``path`` is a usable compiled journal-quality DB.++ Read-only boolean view of ``journal_db_file_status``: both INVALID+ and UNOPENABLE report False, since neither can be served as-is.+ Callers that would DESTROY the file on False must use the status+ function instead and leave an UNOPENABLE file alone.+ """+ return journal_db_file_status(path) == JOURNAL_DB_VALID++# ---------------------------------------------------------------------------# Read-only accessor# ---------------------------------------------------------------------------@@ -166,11 +309,14 @@ class JournalQualityDB:# eats the ?mode=ro&immutable=1 query string before it can# reach sqlite3. The creator builds the connection directly# with the SQLite URI flags intact.+ # Percent-encoded, empty-authority URI (see+ # ``sqlite_readonly_uri``): a raw ``f"file:{path}?..."`` lets+ # a ``?``/``#`` in the data directory truncate the URI and+ # drop mode=ro/immutable, and mis-decodes a literal ``%XX``.+ engine_uri = sqlite_readonly_uri(path.resolve(), immutable=True)+def _make_ro_conn() -> sqlite3.Connection:- return sqlite3.connect(- f"file:{path}?mode=ro&immutable=1",- uri=True,- )+ return sqlite3.connect(engine_uri, uri=True)# NullPool: each Session checks out an isolated read-only# connection that is closed when the session context exits.@@ -236,37 +382,33 @@ class JournalQualityDB:def _validate_existing_db(self, path: Path) -> bool:"""Return True if the existing DB file is usable as-is.- A version of 0 means the file was built before schema stamping- existed and is grandfathered in — we don't force a rebuild just- because the stamp is missing. A non-zero version that doesn't- match the current schema is a real drift signal and triggers a- rebuild. File-open errors also trigger a rebuild.+ Thin wrapper over the module-level ``journal_db_file_status``+ probe plus the destructive half: a file that opened but is+ unusable is removed here so the caller's rebuild starts from a+ clean slate. A file that exists but could not be opened at all+ is left alone and raises ``FileNotFoundError`` (reference DB+ unavailable) instead. Callers+ that only want to KNOW whether the file is usable — a read route+ deciding whether a read would trigger a build — must use the+ probe directly rather than this method, which would delete their+ DB as a side effect of asking."""- from ..utilities.resource_utils import safe_close-- conn: Optional[sqlite3.Connection] = None- is_valid = False- try:- conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)- version = conn.execute("PRAGMA user_version").fetchone()[0]- if version != 0 and version != JOURNAL_QUALITY_SCHEMA_VERSION:- logger.warning(- f"journal_quality.db schema_version={version}, "- f"expected {JOURNAL_QUALITY_SCHEMA_VERSION} — "- f"rebuilding"- )- else:- # Cheap sanity check — confirms the file is a valid DB.- conn.execute("SELECT 1 FROM sqlite_master LIMIT 1").fetchone()- is_valid = True- except (sqlite3.DatabaseError, OSError):- logger.exception(- f"journal_quality.db at {path} is unusable; rebuilding"+ status = journal_db_file_status(path)+ if status == JOURNAL_DB_UNOPENABLE:+ # The file exists but could not even be opened read-only, so+ # nothing says its contents are bad. Unlinking it (and then+ # rebuilding or re-downloading over it) would destroy a+ # possibly-valid DB over a permissions / path-form problem;+ # under a forbidding egress scope the rebuild would then+ # refuse and leave the user with no DB at all. Report the+ # reference DB as unavailable instead — FileNotFoundError is+ # the signal every reader here already degrades on — and+ # leave the file in place.+ raise FileNotFoundError(+ f"{DB_FILENAME} exists at {path} but could not be opened "+ f"read-only; leaving it in place rather than rebuilding")- finally:- if conn is not None:- safe_close(conn, "journal_quality validate")-+ is_valid = status == JOURNAL_DB_VALIDif not is_valid:self._unlink_unusable_db(path)return is_valid@@ -328,7 +470,38 @@ class JournalQualityDB:from .downloader import ensure_journal_datamock_mode = testing_with_mocks()- data_dir, available = ensure_journal_data(auto_download=not mock_mode)+ # Third gate, alongside mock mode: the active egress scope. The+ # dataset sources (OpenAlex/DOAJ/GitHub) are all public, so under+ # PRIVATE_ONLY/STRICT the lazy build must refuse the network+ # download, like the dashboard button and the filter's background+ # fetch already do. The parity is close but not exact, and the+ # difference matters: both siblings resolve the user's PERSISTED+ # settings (the button the literal `policy.egress_scope`, the+ # filter that scope with ADAPTIVE resolved against the primary+ # engine) and fail closed when the scope cannot be parsed,+ # while this gate can only see a context armed on the calling+ # thread. Where no context is armed it allows the download —+ # request threads (Starlette runs sync routes on a threadpool+ # that arms none) and a run whose settings snapshot failed to+ # resolve (`search_system.py` deliberately leaves the backstop+ # unarmed there) both land in that case. Entry points that can+ # reach the persisted settings gate on them themselves: the+ # dashboard read routes in `web/routers/metrics.py` resolve the+ # scope a run would get (ADAPTIVE included), since a page load+ # would otherwise reach this build ungated.+ # A purely local build from already-present snapshots stays+ # allowed — only the network is off the table.+ from ..security.egress.audit_hook import get_active_context+ from ..security.egress.policy import EgressScope++ ctx = get_active_context()+ scope_forbids_public = ctx is not None and ctx.scope in (+ EgressScope.PRIVATE_ONLY,+ EgressScope.STRICT,+ )+ data_dir, available = ensure_journal_data(+ auto_download=not mock_mode and not scope_forbids_public+ )if not available:if mock_mode:raise FileNotFoundError(@@ -339,6 +512,22 @@ class JournalQualityDB:"snapshots in the data directory, if this test needs ""real data.")+ if scope_forbids_public:+ # Recorded here rather than next to the gate above: with+ # the snapshots already on disk `ensure_journal_data`+ # reports them available and the local build proceeds, so+ # nothing was refused and no policy record is due.+ logger.bind(policy_audit=True).info(+ "journal-data lazy build refused the network download: "+ "active egress scope forbids public fetches"+ )+ raise FileNotFoundError(+ "Journal data files not available and the active "+ "egress scope forbids the public download. Place "+ "the gz snapshots in the data directory, or change "+ "the egress scope and then download from the "+ "dashboard."+ )raise FileNotFoundError("Journal data files not available. ""Check your network connection or download manually "@@ -1111,8 +1300,20 @@ def build_db(f"{output_path.name}.tmp-{os.getpid()}-{secrets.token_hex(4)}")- write_url = f"sqlite:///{tmp_path}"- engine = create_engine(write_url, connect_args={"check_same_thread": False})+ # Connect by plain filename through a creator, never via a+ # ``sqlite:///{tmp_path}`` URL: SQLAlchemy's URL parser treats a+ # ``?`` in the data-directory name as the start of a query string,+ # so the writer would open (and create) a truncated path and the+ # final ``os.replace`` would fail. A plain (non-URI) filename has no+ # delimiters. QueuePool is what the URL form selected for a file DB.+ from sqlalchemy.pool import QueuePool++ def _make_write_conn() -> sqlite3.Connection:+ return sqlite3.connect(os.fspath(tmp_path), check_same_thread=False)++ engine = create_engine(+ "sqlite://", creator=_make_write_conn, poolclass=QueuePool+ )try:# Pragmas for fast bulk insert. `journal_mode = OFF` plus@@ -1214,7 +1415,10 @@ def build_db(elapsed = time.time() - startsize_mb = output_path.stat().st_size / (1024 * 1024)with closing(- sqlite3.connect(f"file:{output_path}?mode=ro&immutable=1", uri=True)+ sqlite3.connect(+ sqlite_readonly_uri(Path(output_path).resolve(), immutable=True),+ uri=True,+ )) as _count_conn:source_count = _count_conn.execute("SELECT COUNT(*) FROM sources"@@ -1281,7 +1485,11 @@ def _load_gzip_json(path: Path) -> dict:def _load_openalex(data_dir: Path) -> dict:- path = data_dir / "openalex_sources.json.gz"+ # Lazy import to avoid any downloader <-> db module-level cycle,+ # matching the other lazy imports of `.downloader` in this file.+ from .downloader import REQUIRED_SNAPSHOT_FILENAME++ path = data_dir / REQUIRED_SNAPSHOT_FILENAMEif not path.exists():raise FileNotFoundError(f"OpenAlex source file not found: {path}")data = _load_gzip_json(path)diff --git a/src/local_deep_research/journal_quality/downloader.py b/src/local_deep_research/journal_quality/downloader.pyindex c7f10e2c6d..b247ff64c2 100644--- a/src/local_deep_research/journal_quality/downloader.py+++ b/src/local_deep_research/journal_quality/downloader.py@@ -9,6 +9,7 @@ endpoint.Public API (kept stable for existing callers and tests):- `JOURNAL_DATA_VERSION`+- `REQUIRED_SNAPSHOT_FILENAME`- `get_journal_data_status()`- `download_journal_data(force=False)`- `ensure_journal_data(auto_download=True)`@@ -36,6 +37,16 @@ from .data_sources import ALL_SOURCES, get_sourceJOURNAL_DATA_VERSION = "v4"+#: The one REQUIRED snapshot, and therefore the predicate that decides+#: whether a journal-DB build needs the network at all: with this file in+#: the data directory ``ensure_journal_data`` reports "available" without+#: a single request and ``JournalQualityDB._build_or_raise`` compiles+#: straight from disk. Named here rather than repeated as a literal so+#: the callers that PREDICT a download — ``web/routers/metrics.py``'s+#: ``_journal_ref_db_read_would_download`` — cannot drift from the caller+#: that performs one.+REQUIRED_SNAPSHOT_FILENAME = "openalex_sources.json.gz"+_SENTINEL = ".downloading"@@ -227,6 +238,11 @@ def get_journal_data_status() -> dict:"data_dir": str,}"""+ # Lazy import to avoid any downloader <-> db module-level cycle,+ # matching the existing db.py -> downloader.py lazy imports for this+ # same pair (`_warn_on_stale_data_version`, `_build_or_raise`).+ from .db import DB_FILENAME, journal_db_file_is_valid+data_dir = _get_data_dir()version_file = data_dir / "version.json"@@ -243,12 +259,24 @@ def get_journal_data_status() -> dict:sources = [src.status_dict(data_dir) for src in ALL_SOURCES]# Available if the (required) OpenAlex source exists OR the compiled- # reference DB exists. The compiled DB is useful even when the source- # JSON has been deleted, since the dashboard can still query it.- has_source = files.get("openalex_sources.json.gz", False)- has_db = (data_dir / "journal_quality.db").exists() or (- data_dir / "journal_reference.db"- ).exists()+ # reference DB exists AND is usable. The compiled DB is useful even+ # when the source JSON has been deleted, since the dashboard can+ # still query it — but a file that merely EXISTS while being+ # unreadable (stale schema, corrupt) must not count: every actual+ # read would rebuild it (or, under a forbidding egress scope,+ # refuse) instead of serving it, so reporting "available" here would+ # hide the install banner behind a file that answers with silent+ # zeros. `journal_reference.db` is the pre-rename legacy filename+ # the downloader below deletes after a fresh download; an install+ # that hasn't gone through one yet is checked the same way. The+ # `exists()` guard keeps an absent file (the usual case for the+ # legacy name, and for both on first run) a quiet "not present":+ # the validator logs an exception traceback on any open failure.+ has_source = files.get(REQUIRED_SNAPSHOT_FILENAME, False)+ has_db = any(+ path.exists() and journal_db_file_is_valid(path)+ for path in (data_dir / DB_FILENAME, data_dir / "journal_reference.db")+ )return {"available": has_source or has_db,@@ -635,11 +663,16 @@ def ensure_journal_data(the cached answer for 30 seconds. The success path (data filespresent) is already fast — we only cache the negative / raceresult, which is the noisy path.++ A caller that is not allowed to download never writes the cache:+ it attempted nothing worth memoising, and the entry carries no+ record of which question it answered, so it would go on to answer+ callers that ARE allowed to download."""global _ensure_cacheuser_dir = _get_data_dir()- if (user_dir / "openalex_sources.json.gz").exists():+ if (user_dir / REQUIRED_SNAPSHOT_FILENAME).exists():# Positive path is cheap (one stat call) — no need to cache.return user_dir, True@@ -649,16 +682,25 @@ def ensure_journal_data(if now - ts < _ENSURE_CACHE_TTL:return cached- if auto_download:- logger.info(- "Journal data not found — fetching from upstream sources..."- )- success, message = download_journal_data()- if success:- logger.info(message)- _ensure_cache = (now, (user_dir, True))- return user_dir, True- logger.warning(f"Journal data fetch failed: {message}")+ if not auto_download:+ # Refusals (test mock mode, or a lazy build whose egress scope+ # forbids the public fetch) deliberately do NOT populate the+ # cache. The cached tuple records no trace of which question it+ # answered, so caching this one would answer the next 30 seconds+ # of ensure_journal_data(auto_download=True) calls — another+ # user's search, whose scope permits the fetch — with a stale+ # "unavailable" and silently suppress a legitimate download.+ # Nothing is lost: this branch performed a single stat, not the+ # download/sentinel race the cache exists to absorb.+ return None, False++ logger.info("Journal data not found — fetching from upstream sources...")+ success, message = download_journal_data()+ if success:+ logger.info(message)+ _ensure_cache = (now, (user_dir, True))+ return user_dir, True+ logger.warning(f"Journal data fetch failed: {message}")result: tuple[Optional[Path], bool] = (None, False)_ensure_cache = (now, result)diff --git a/src/local_deep_research/web/routers/metrics.py b/src/local_deep_research/web/routers/metrics.pyindex c19a4abb1f..6e7b6ce908 100644--- a/src/local_deep_research/web/routers/metrics.py+++ b/src/local_deep_research/web/routers/metrics.py@@ -2441,6 +2441,177 @@ _journals_read_limit = limiter.shared_limit()+def _resolve_persisted_egress_scope(username: str) -> tuple[Any, Any]:+ """Resolve the user's persisted ``policy.egress_scope``.++ Returns ``(scope, scope_raw)``. ``scope`` is an ``EgressScope``, or+ ``None`` when the stored value cannot be parsed — every caller treats+ that as "fail closed". ``scope_raw`` is the stored value (with the+ retired ``both`` rewritten to ``adaptive``) and exists only for the+ audit log.++ Sync on purpose: it opens the user's SQLCipher settings session, so+ async callers hand it to ``run_db_sync`` instead of the event loop.+ """+ from ...security.egress.policy import (+ DEFAULT_EGRESS_SCOPE,+ EgressScope,+ PolicyDeniedError,+ parse_user_egress_scope,+ )+ from ...utilities.db_utils import get_settings_manager++ scope_raw = get_settings_manager(username=username).get_setting(+ "policy.egress_scope", DEFAULT_EGRESS_SCOPE+ )+ # Retired "both" reads as the adaptive default, mirroring+ # context_from_snapshot's read-time backstop for un-migrated rows.+ if str(scope_raw).strip().lower() == EgressScope.BOTH.value:+ scope_raw = EgressScope.ADAPTIVE.value+ try:+ # Stale "unprotected" rows fall back to adaptive when the+ # operator gate is off, matching every other runtime reader.+ scope = parse_user_egress_scope(+ scope_raw, disabled_unprotected="adaptive"+ )+ except PolicyDeniedError:+ scope = None # corrupt scope -> callers fail closed+ return scope, scope_raw+++def _egress_scope_forbids_public_fetch(scope: Any) -> bool:+ """Whether ``scope`` rules out fetching the public journal datasets.++ ``None`` — an unparseable stored value — fails closed, like every+ other runtime reader of this setting.+ """+ from ...security.egress.policy import EgressScope++ return scope is None or scope in (+ EgressScope.PRIVATE_ONLY,+ EgressScope.STRICT,+ )+++def _resolve_effective_egress_scope(username: str) -> Any:+ """Resolve the egress scope a research run for ``username`` would get.++ Unlike ``_resolve_persisted_egress_scope``, which returns the literal+ stored value, this resolves ADAPTIVE against the user's primary+ search engine through ``build_run_egress_context`` — the seam the+ research worker uses to arm a run's context, and the same+ ``context_from_snapshot`` resolution the reputation filter's+ ``_should_skip_journal_fetch_for_scope`` applies. Under the default+ ADAPTIVE scope a private primary (a library/collection engine or a+ per-user private retriever) resolves PRIVATE_ONLY, so a read route+ that only looked at the literal ``adaptive`` would start a public+ download those siblings refuse.++ Raises on any resolution failure (unreadable settings, an unparseable+ scope, no primary engine configured); the caller fails closed.++ Sync on purpose: it opens the user's SQLCipher settings session.+ """+ from ...security.egress.policy import build_run_egress_context+ from ...utilities.db_utils import get_settings_manager++ snapshot = get_settings_manager(username=username).get_settings_snapshot(+ strict=True+ )+ if not isinstance(snapshot, dict):+ raise TypeError(+ f"settings snapshot must be a dict, got {type(snapshot).__name__}"+ )+ primary = snapshot.get("search.tool")+ if isinstance(primary, dict):+ primary = primary.get("value")+ return build_run_egress_context(+ snapshot,+ primary if isinstance(primary, str) else None,+ username=username,+ ).scope+++def _journal_ref_db_read_would_download(username: str) -> bool:+ """Whether reading the reference DB would fetch the public datasets.++ ``JournalQualityDB._ensure_engine`` lazily BUILDS the reference DB on+ TWO conditions, not one: when the file is missing, and when an+ existing file fails ``_validate_existing_db`` — which every install+ hits the first time it runs after a ``JOURNAL_QUALITY_SCHEMA_VERSION``+ bump (three have shipped) or after the file is corrupted. That build+ downloads several hundred MB from OpenAlex/DOAJ/GitHub *unless it has+ local snapshots to compile from*. The build's own egress gate reads+ the context armed on the calling thread, but these routes are sync+ handlers that Starlette runs on an anyio threadpool worker where+ nothing arms one — so that gate is a no-op here and a plain dashboard+ page load would start the download.++ The predicate that actually governs the download is therefore the+ SNAPSHOT, not the compiled DB, and this function answers it in that+ order:++ 1. ``REQUIRED_SNAPSHOT_FILENAME`` present in the journal data+ directory → ``ensure_journal_data`` reports "available" after one+ stat and the build compiles from disk. Never a download, so never+ blocked, whatever the scope. (A forbidding scope must not turn an+ offline rebuild into a dark dashboard.)+ 2. No snapshot, but the compiled DB exists AND passes the same+ validity probe ``_ensure_engine`` applies → no build runs at all,+ so not blocked. The probe is ``journal_db_file_is_valid``, the+ read-only half of ``_validate_existing_db``: it opens the file+ ``mode=ro``, reads ``PRAGMA user_version`` and ``sqlite_master``,+ and — unlike the method — does not unlink an unusable file, so+ asking the question cannot destroy the user's DB or start a build.+ 3. Otherwise a read WOULD have to download. Resolve the scope a+ research run for this user would get — ``policy.egress_scope``+ with ADAPTIVE resolved against the user's primary search engine+ (``_resolve_effective_egress_scope``) — so the caller can answer+ "unavailable" rather than fetch. Any resolution failure (corrupt+ scope, no primary engine, unreadable settings) fails closed.++ Only case 3 opens the settings session, and only case 2 opens the+ SQLite file, so the healthy dashboard still costs one stat.+ """+ from ...config.paths import get_journal_data_directory+ from ...journal_quality.db import DB_FILENAME, journal_db_file_is_valid+ from ...journal_quality.downloader import REQUIRED_SNAPSHOT_FILENAME++ try:+ data_dir = get_journal_data_directory()+ if (data_dir / REQUIRED_SNAPSHOT_FILENAME).exists():+ return False+ db_path = data_dir / DB_FILENAME+ if db_path.exists() and journal_db_file_is_valid(db_path):+ return False+ except Exception:+ # Reads fail closed on an unreadable journal data directory. That+ # has not been logged by the time it gets here — `_ensure_dir` mkdirs with `label=None` and logs+ # nothing, and `get_data_directory` raises its `LDR_DATA_DIR`+ # ValueError unlogged — so log it here rather than swallow a+ # misconfigured deployment into a silent 503. Fail closed because+ # this is exactly the case where the fetch cannot be shown to be+ # allowed: the read degrades to "unavailable" instead of starting+ # the download.+ logger.exception(+ "journal reference DB egress pre-check failed; treating the "+ "read as blocked"+ )+ return True+ try:+ scope = _resolve_effective_egress_scope(username)+ except Exception as exc:+ # Fail closed, but WITHOUT a traceback: the frames below hold the+ # user's full settings snapshot (API keys included), which a+ # diagnose-mode traceback would render. Type name only.+ logger.bind(policy_audit=True).warning(+ "journal reference DB egress scope unresolvable "+ f"({type(exc).__name__}); treating the read as blocked"+ )+ return True+ return _egress_scope_forbids_public_fetch(scope)++@router.get("/journals")def journal_quality(request: Request, username: Annotated[str, Depends(require_auth)]@@ -2498,37 +2669,12 @@ async def api_journal_data_download(# auto-download path is already gated by# JournalReputationFilter._should_skip_journal_fetch_for_scope; this# closes the manual button as the matching entry point.- from ...security.egress.policy import (- DEFAULT_EGRESS_SCOPE,- EgressScope,- PolicyDeniedError,- parse_user_egress_scope,- )- from ...utilities.db_utils import get_settings_manager-# Settings read opens the user's SQLCipher session (sync) — keep it# off the event loop.- scope_raw = await run_db_sync(- lambda: get_settings_manager(username=username).get_setting(- "policy.egress_scope", DEFAULT_EGRESS_SCOPE- )+ scope, scope_raw = await run_db_sync(+ lambda: _resolve_persisted_egress_scope(username))- # Retired "both" reads as the adaptive default, mirroring- # context_from_snapshot's read-time backstop for un-migrated rows.- if str(scope_raw).strip().lower() == EgressScope.BOTH.value:- scope_raw = EgressScope.ADAPTIVE.value- try:- # Stale "unprotected" rows fall back to adaptive when the- # operator gate is off, matching every other runtime reader.- scope = parse_user_egress_scope(- scope_raw, disabled_unprotected="adaptive"- )- except PolicyDeniedError:- scope = None # corrupt scope -> fail closed below- if scope is None or scope in (- EgressScope.PRIVATE_ONLY,- EgressScope.STRICT,- ):+ if _egress_scope_forbids_public_fetch(scope):logger.bind(policy_audit=True).warning("journal data download refused by egress policy",scope=str(scope_raw),@@ -2654,8 +2800,16 @@ def api_journal_quality(try:from ...journal_quality.db import get_journal_reference_db+ # Egress policy: ``ref.available`` lazily BUILDS the reference DB+ # when the file is missing OR fails validation, and that build+ # downloads several hundred MB of public data unless the local+ # snapshots are already on disk. Resolve the user's effective+ # scope (ADAPTIVE resolved against the primary engine) FIRST, before anything touches the engine, and answer+ # with the same 503 this route already returns for an+ # unavailable reference DB.+ blocked = _journal_ref_db_read_would_download(username)ref = get_journal_reference_db()- if not ref.available:+ if blocked or not ref.available:return JSONResponse({"status": "error",@@ -2871,8 +3025,21 @@ def api_user_research_journals(A re-scored journal propagates to existing research rowsautomatically because no per-Paper score is stored."""+ # `reference_data_available` distinguishes "no predatory journals+ # found" from "predatory journals were never checked for". The+ # reference DB can be withheld from this route entirely — an egress+ # scope that forbids the public fetch, or a build/open failure — and+ # `predatory_blocked: 0` alongside `status: success` would otherwise+ # read as a clean bill of health. The route's own comment on the+ # `predatory_blocked` query calls silently undercounting predatory+ # journals a no-fallbacks violation; this is the same undercount at+ # the response level, so it is flagged rather than hidden. It is+ # False on this early-return shape because every branch that reaches+ # it (no papers table, no rows) returns before the reference DB is+ # consulted: there is nothing to have checked._empty_response = {"status": "success",+ "reference_data_available": False,"summary": {"total_journals": 0,"avg_quality": None,@@ -2918,7 +3085,30 @@ def api_user_research_journals(# One batched ref-DB lookup for the whole top-200 slice —# hits `sources.name_lower IN (…)` rather than 200 point# queries.- ref_db = _get_ref_db_or_none()+ # Egress policy: every reference-DB read below lazily BUILDS+ # the DB when the file is missing or fails validation, and+ # with no local snapshots that build downloads several+ # hundred MB of public data on a threadpool worker where the+ # build's own scope gate is blind (see+ # _journal_ref_db_read_would_download). Under a forbidding+ # effective scope, degrade to the enrichment-free response+ # this route already returns when the reference DB is+ # unavailable.+ ref_db = (+ None+ if _journal_ref_db_read_would_download(username)+ else _get_ref_db_or_none()+ )+ # `_get_ref_db_or_none` hands back the singleton without+ # opening anything, and the lookups below swallow a failed+ # lazy build/open (FileNotFoundError) into an empty result —+ # so a non-None handle alone would report "checked, none+ # found" for a DB that was never read. `available` runs the+ # same lazy open the lookups run (the egress gate above has+ # already ruled out a forbidden download) and is False on+ # exactly the failure they swallow; drop the handle then.+ if ref_db is not None and not ref_db.available:+ ref_db = Noneenrich_map = {}if ref_db is not None:enrich_map = ref_db.lookup_sources_batch(@@ -3004,6 +3194,13 @@ def api_user_research_journals(return {"status": "success",+ # False whenever `ref_db` was None — the egress gate withheld+ # it, `_get_ref_db_or_none` failed, or the reference DB could+ # not be opened/built (`available` False). Then+ # `predatory_blocked` is 0 because nothing was checked, not+ # because nothing was found, and every bibliometric field on+ # every journal row is absent for the same reason.+ "reference_data_available": ref_db is not None,"summary": {"total_journals": total_journals,"avg_quality": avg_quality,@@ -3040,8 +3237,21 @@ def api_research_journals(Mirrors the response shape of /api/journals/user-research so thedashboard can reuse its rendering code."""+ # `reference_data_available` distinguishes "no predatory journals+ # found" from "predatory journals were never checked for". The+ # reference DB can be withheld from this route entirely — an egress+ # scope that forbids the public fetch, or a build/open failure — and+ # `predatory_blocked: 0` alongside `status: success` would otherwise+ # read as a clean bill of health. The route's own comment on the+ # `predatory_blocked` query calls silently undercounting predatory+ # journals a no-fallbacks violation; this is the same undercount at+ # the response level, so it is flagged rather than hidden. It is+ # False on this early-return shape because every branch that reaches+ # it (no papers table, no rows) returns before the reference DB is+ # consulted: there is nothing to have checked._empty_response = {"status": "success",+ "reference_data_available": False,"summary": {"total_journals": 0,"avg_quality": None,@@ -3107,7 +3317,30 @@ def api_research_journals(if not rows:return _empty_response- ref_db = _get_ref_db_or_none()+ # Egress policy: every reference-DB read below lazily BUILDS+ # the DB when the file is missing or fails validation, and+ # with no local snapshots that build downloads several+ # hundred MB of public data on a threadpool worker where the+ # build's own scope gate is blind (see+ # _journal_ref_db_read_would_download). Under a forbidding+ # effective scope, degrade to the enrichment-free response+ # this route already returns when the reference DB is+ # unavailable.+ ref_db = (+ None+ if _journal_ref_db_read_would_download(username)+ else _get_ref_db_or_none()+ )+ # `_get_ref_db_or_none` hands back the singleton without+ # opening anything, and the lookups below swallow a failed+ # lazy build/open (FileNotFoundError) into an empty result —+ # so a non-None handle alone would report "checked, none+ # found" for a DB that was never read. `available` runs the+ # same lazy open the lookups run (the egress gate above has+ # already ruled out a forbidden download) and is False on+ # exactly the failure they swallow; drop the handle then.+ if ref_db is not None and not ref_db.available:+ ref_db = Noneenrich_map = {}if ref_db is not None:enrich_map = ref_db.lookup_sources_batch(@@ -3164,6 +3397,12 @@ def api_research_journals(return {"status": "success",+ # Same marker as /api/journals/user-research, whose response+ # shape this route deliberately mirrors: False means+ # `predatory_blocked` counts nothing because the reference DB+ # was never consulted, not because this research session is+ # clean.+ "reference_data_available": ref_db is not None,"summary": {"total_journals": len(journals),"avg_quality": avg_quality,diff --git a/src/local_deep_research/web/templates/pages/journal_quality.html b/src/local_deep_research/web/templates/pages/journal_quality.htmlindex 9dbe6fbe7d..6ca0babe2e 100644--- a/src/local_deep_research/web/templates/pages/journal_quality.html+++ b/src/local_deep_research/web/templates/pages/journal_quality.html@@ -1208,7 +1208,15 @@ async function loadUserResearchJournals() {document.getElementById('yr-stat-avg-quality').textContent =s.avg_quality != null ? s.avg_quality : '—';document.getElementById('yr-stat-papers').textContent = s.total_papers;- document.getElementById('yr-stat-predatory').textContent = s.predatory_blocked;+ // `reference_data_available: false` means the reference DB was never+ // consulted (its egress scope forbids the public fetch, or it could+ // not be opened), so `predatory_blocked` is 0 for want of data, not+ // because none were found. Render the same em dash the unknown+ // average quality above uses rather than a reassuring zero. Older+ // payloads omit the field, so only an explicit `false` suppresses+ // the count.+ document.getElementById('yr-stat-predatory').textContent =+ result.reference_data_available === false ? '—' : s.predatory_blocked;document.getElementById('yr-table-count').textContent = result.journals.length;content.style.display = 'block';diff --git a/tests/journal_quality/test_db_accessors.py b/tests/journal_quality/test_db_accessors.pyindex cc51c165b2..7e45330438 100644--- a/tests/journal_quality/test_db_accessors.py+++ b/tests/journal_quality/test_db_accessors.py@@ -10,15 +10,23 @@ test_db.py) and temp-file fixtures for filesystem utilities.import osimport sqlite3import time+from pathlib import PurePosixPath, PureWindowsPath+from unittest.mock import patchimport pytestfrom local_deep_research.journal_quality.db import (+ JOURNAL_DB_UNOPENABLE,JOURNAL_QUALITY_SCHEMA_VERSION,JournalQualityDB,_sweep_stale_tmp_files,+ journal_db_file_is_valid,+ journal_db_file_status,+ sqlite_readonly_uri,)+_JQ_DB_MODULE = "local_deep_research.journal_quality.db"+# PLoS ONE — open access, in DOAJ since the registry's early days, so a# stable positive example. Nature is a subscription journal and therefore# absent from DOAJ — a stable negative example that exists in the sources@@ -375,6 +383,158 @@ class TestValidateExistingDb:assert _uninitialized_db()._validate_existing_db(db_path) is False+ def test_hostile_characters_in_directory_path(self, tmp_path):+ """A data directory containing '?', '#', '%' or a space must not+ truncate the SQLite URI.++ The probe used to build the URI by interpolating the raw path+ into ``f"file:{path}?mode=ro"``. A literal ``?`` or ``#`` in the+ directory name ends the URI's path component early — SQLite+ parses everything from there on as query string / fragment —+ which drops ``mode=ro`` and, since the truncated path usually+ doesn't already exist, opens (and creates) a stray file there+ instead of reading the real database. ``sqlite_readonly_uri``+ percent-encodes those characters so the whole path round-trips.+ """+ hostile_dir = tmp_path / "x?y#z%41 w"+ hostile_dir.mkdir()+ db_path = hostile_dir / "test.db"+ conn = sqlite3.connect(str(db_path))+ conn.execute(+ "PRAGMA user_version = %d" % JOURNAL_QUALITY_SCHEMA_VERSION+ )+ conn.execute("CREATE TABLE t (x)")+ conn.commit()+ conn.close()++ before = {+ str(p.relative_to(tmp_path))+ for p in tmp_path.rglob("*")+ if p.is_file()+ }++ assert _uninitialized_db()._validate_existing_db(db_path) is True++ after = {+ str(p.relative_to(tmp_path))+ for p in tmp_path.rglob("*")+ if p.is_file()+ }+ assert after == before, (+ "validating a DB in a hostile-character directory must not "+ "create (or remove) any file, inside the directory or as a "+ "truncated-path sibling of it"+ )++ def test_open_failure_on_an_existing_file_does_not_delete_it(+ self, tmp_path+ ):+ """An existing DB that cannot even be OPENED must be left alone.++ A failed open says nothing about the file's contents — it is a+ permissions problem, an unreachable share, or (the regression+ this pins) a URI form SQLite refuses: ``Path.as_uri()`` turns a+ Windows UNC path into ``file://server/share/...`` and SQLite+ rejects that authority. Treating the open failure as corruption+ made ``_validate_existing_db`` unlink a valid DB on every init.+ """+ db_path = tmp_path / "test.db"+ conn = sqlite3.connect(str(db_path))+ conn.execute(+ "PRAGMA user_version = %d" % JOURNAL_QUALITY_SCHEMA_VERSION+ )+ conn.execute("CREATE TABLE t (x)")+ conn.commit()+ conn.close()++ with patch(+ f"{_JQ_DB_MODULE}.sqlite3.connect",+ side_effect=sqlite3.OperationalError(+ "invalid uri authority: server"+ ),+ ):+ assert journal_db_file_status(db_path) == JOURNAL_DB_UNOPENABLE+ assert journal_db_file_is_valid(db_path) is False+ with pytest.raises(FileNotFoundError):+ _uninitialized_db()._validate_existing_db(db_path)++ assert db_path.exists(), (+ "a DB that merely could not be opened was deleted as if it "+ "were corrupt"+ )+ assert _uninitialized_db()._validate_existing_db(db_path) is True+++class TestSqliteReadonlyUri:+ """The probe's URI must open on every path form SQLite can be handed.++ SQLite accepts only an empty or ``localhost`` authority (stock+ builds lack ``SQLITE_ALLOW_URI_AUTHORITY``), so a UNC host must go+ into the path — ``file:////server/share`` — never the authority.+ """++ def test_posix_path_percent_encodes_uri_delimiters(self):+ uri = sqlite_readonly_uri(PurePosixPath("/data/x?y#z%41 w é/j.db"))+ assert uri == ("file:///data/x%3Fy%23z%2541%20w%20%C3%A9/j.db?mode=ro")++ @pytest.mark.skipif(+ os.name == "nt",+ reason="non-UTF-8 filesystem bytes in a str path are POSIX-only",+ )+ def test_posix_non_utf8_bytes_are_percent_encoded_verbatim(self):+ # b"\xe9" is not valid UTF-8, so on POSIX it decodes to the lone+ # surrogate "\udce9"; quote(str) would raise UnicodeEncodeError.+ # The URI must carry the exact on-disk byte, %E9, not a UTF-8+ # re-encoding of some substitute character.+ path = PurePosixPath(os.fsdecode(b"/data\xe9 ?#/j.db"))+ uri = sqlite_readonly_uri(path)+ assert uri == "file:///data%E9%20%3F%23/j.db?mode=ro"++ def test_immutable_flag_appends_engine_query(self):+ uri = sqlite_readonly_uri(+ PurePosixPath("/data/x?y#z%41 w/j.db"), immutable=True+ )+ assert uri == (+ "file:///data/x%3Fy%23z%2541%20w/j.db?mode=ro&immutable=1"+ )++ def test_windows_drive_path(self):+ uri = sqlite_readonly_uri(PureWindowsPath(r"C:\Users\a b\j.db"))+ assert uri == "file:///C:/Users/a%20b/j.db?mode=ro"++ def test_windows_unc_path_uses_an_empty_authority(self):+ uri = sqlite_readonly_uri(+ PureWindowsPath(r"\\server\share\x?y#z%41\j.db")+ )+ assert uri == "file:////server/share/x%3Fy%23z%2541/j.db?mode=ro"++ @pytest.mark.skipif(+ os.name == "nt",+ reason="the four-slash rewrite of a drive path is POSIX-only",+ )+ def test_generated_forms_open_and_authority_form_does_not(self, tmp_path):+ hostile_dir = tmp_path / "x?y#z%41 w é"+ hostile_dir.mkdir()+ db_path = hostile_dir / "j.db"+ conn = sqlite3.connect(str(db_path))+ conn.execute("CREATE TABLE t (x)")+ conn.commit()+ conn.close()++ uri = sqlite_readonly_uri(db_path)+ # Same file through the four-slash (UNC-shaped) form: an empty+ # authority with a path starting "//", which POSIX resolves to+ # the same file — so SQLite demonstrably parses that shape.+ four_slash = "file:/" + uri[len("file:") :]+ assert four_slash.startswith("file:////")+ for candidate in (uri, four_slash):+ with sqlite3.connect(candidate, uri=True) as c:+ assert c.execute("SELECT count(*) FROM t").fetchone() == (0,)+ c.close()++ with pytest.raises(sqlite3.OperationalError, match="authority"):+ sqlite3.connect("file://server" + uri[len("file://") :], uri=True)+# ---------------------------------------------------------------------------# _sweep_stale_tmp_files (temp-file tests)diff --git a/tests/journal_quality/test_db_offline_accessors.py b/tests/journal_quality/test_db_offline_accessors.pyindex 2637ef688c..fcc63002b2 100644--- a/tests/journal_quality/test_db_offline_accessors.py+++ b/tests/journal_quality/test_db_offline_accessors.py@@ -381,9 +381,9 @@ def test_session_database_error_resets_cached_engine(@pytest.mark.parametrize(("mock_mode", "message"),(- # The two branches at db.py:333-345 share the substring "not- # available", which doesn't distinguish them — match on the- # branch-specific wording instead.+ # Every FileNotFoundError branch in `_build_or_raise` shares the+ # substring "not available", which doesn't distinguish them —+ # match on the branch-specific wording instead.(True, "LDR_TESTING_WITH_MOCKS"),(False, "Check your network"),),diff --git a/tests/journal_quality/test_db_offline_build.py b/tests/journal_quality/test_db_offline_build.pyindex fdc881d645..f5d9d913b7 100644--- a/tests/journal_quality/test_db_offline_build.py+++ b/tests/journal_quality/test_db_offline_build.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport gzipimport json+import osimport sqlite3import statfrom contextlib import closing@@ -22,6 +23,7 @@ from sqlalchemy.exc import OperationalErrorfrom local_deep_research.journal_quality import db as db_modulefrom local_deep_research.journal_quality.db import (+ JOURNAL_DB_VALID,JOURNAL_QUALITY_SCHEMA_VERSION,JournalQualityDB,_load_abbreviations,@@ -30,6 +32,7 @@ from local_deep_research.journal_quality.db import (_load_openalex,_load_predatory,build_db,+ journal_db_file_status,)@@ -226,6 +229,128 @@ def test_built_database_opens_through_read_only_accessor(database.reset()+ "dir_name",+ ["x?y", "x#y", "x%41y", "a b"],+ ids=["question-mark", "hash", "percent-escape", "space"],+)+def test_build_and_engine_open_under_uri_hostile_directory(+ compact_snapshots: Path, monkeypatch: pytest.MonkeyPatch, dir_name: str+) -> None:+ """Every SQLite URI the module builds must survive the data dir name.++ ``build_db``'s post-build count and ``_ensure_engine``'s+ ``_make_ro_conn`` used to interpolate the raw path into+ ``f"file:{path}?mode=ro&immutable=1"``. A ``?`` or ``#`` in a parent+ directory then truncated the URI — dropping ``mode=ro``/``immutable``,+ creating a stray 0-byte file at the truncated path and failing "no+ such table" — while the validity probe (already percent-encoded) said+ VALID. A literal ``%41`` was decoded to ``A``, opening the wrong path.+ Build and engine now share ``sqlite_readonly_uri``.+ """+ hostile = compact_snapshots / dir_name / "inner"+ hostile.mkdir(parents=True)+ output = hostile / "compiled.db"++ def files() -> set[str]:+ return {+ str(p.relative_to(compact_snapshots))+ for p in compact_snapshots.rglob("*")+ if p.is_file()+ }++ before_build = files()+ build_db(data_dir=compact_snapshots, output_path=output)+ after_build = files()+ assert after_build - before_build == {+ str(output.relative_to(compact_snapshots))+ }, "build_db left a file other than its output behind"++ database = JournalQualityDB()+ monkeypatch.setattr(database, "_resolve_db_path", lambda: output)+ try:+ result = database.lookup_openalex(source_id="https://openalex.org/S5")+ assert result is not None+ assert result["name"] == "Duplicate Venue"+ # Still mode=ro through the hostile path: SQLite refuses a write.+ with pytest.raises(OperationalError, match="readonly"):+ with database.session() as session:+ session.execute(+ text(+ "INSERT INTO sources (name, name_lower, "+ "score_source) VALUES ('x', 'x', 'openalex')"+ )+ )+ session.commit()+ finally:+ database.reset()++ assert files() == after_build, (+ "opening the engine created or removed a file — a truncated "+ "file: URI opened a stray path instead of the built DB"+ )+ stray = [+ p+ for p in compact_snapshots.rglob("*")+ if p.is_file() and p.stat().st_size == 0+ ]+ assert stray == [], f"stray 0-byte file(s) created: {stray}"+++ os.name == "nt",+ reason="non-UTF-8 bytes in a directory name are a POSIX-only shape",+)+def test_build_probe_and_engine_open_under_non_utf8_directory(+ compact_snapshots: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A data dir whose name is not valid UTF-8 must still be served.++ On POSIX ``os.fsdecode(b"data\\xe9")`` is ``"data\\udce9"`` (a lone+ surrogate). ``sqlite_readonly_uri`` used to ``quote()`` that ``str``,+ which raises ``UnicodeEncodeError``; the probe then reported the+ valid DB as UNOPENABLE on every access and the engine could not+ open it at all — while a plain ``sqlite3.connect(str_path)`` (and+ the pre-URI code) opened it fine. The URI now carries the exact+ filesystem bytes.+ """+ hostile = compact_snapshots / os.fsdecode(b"data\xe9")+ try:+ hostile.mkdir()+ except (OSError, UnicodeEncodeError):+ pytest.skip("filesystem rejects non-UTF-8 directory names")+ output = hostile / "compiled.db"++ def files() -> set[bytes]:+ return {+ os.fsencode(p.relative_to(compact_snapshots))+ for p in compact_snapshots.rglob("*")+ if p.is_file()+ }++ before_build = files()+ build_db(data_dir=compact_snapshots, output_path=output)+ after_build = files()+ assert after_build - before_build == {+ os.fsencode(output.relative_to(compact_snapshots))+ }, "build_db left a file other than its output behind"++ assert journal_db_file_status(output) == JOURNAL_DB_VALID++ database = JournalQualityDB()+ monkeypatch.setattr(database, "_resolve_db_path", lambda: output)+ try:+ result = database.lookup_openalex(source_id="https://openalex.org/S5")+ assert result is not None+ assert result["name"] == "Duplicate Venue"+ finally:+ database.reset()++ assert files() == after_build, (+ "probing or opening the engine created or removed a file"+ )++def test_optional_loaders_return_empty_when_snapshots_are_absent(tmp_path: Path,) -> None:diff --git a/tests/journal_quality/test_downloader.py b/tests/journal_quality/test_downloader.pyindex bd78804e16..df4b5f80d5 100644--- a/tests/journal_quality/test_downloader.py+++ b/tests/journal_quality/test_downloader.py@@ -6,12 +6,16 @@ from unittest.mock import patchimport pytest+from local_deep_research.journal_quality.db import DB_FILENAMEfrom local_deep_research.journal_quality.downloader import (JOURNAL_DATA_VERSION,download_journal_data,ensure_journal_data,get_journal_data_status,)+from tests.security.test_journal_lazy_build_egress_gate import (+ _write_valid_db,+)@pytest.fixture@@ -37,6 +41,19 @@ class TestGetJournalDataStatus:assert status["version"] is Noneassert status["needs_update"] is True+ def test_missing_db_files_skip_the_validity_probe(self, tmp_data_dir):+ """An absent compiled DB (current or legacy name) is a quiet+ "not present", not a probe call: the probe logs an exception+ traceback on any open failure, which made every status poll log+ misleading errors on installs without the legacy file.+ """+ with patch(+ "local_deep_research.journal_quality.db.journal_db_file_is_valid"+ ) as probe:+ status = get_journal_data_status()+ probe.assert_not_called()+ assert status["available"] is False+def test_files_present(self, tmp_data_dir):_write_openalex(tmp_data_dir)(tmp_data_dir / "doaj_journals.json").write_text("{}")@@ -55,6 +72,27 @@ class TestGetJournalDataStatus:status = get_journal_data_status()assert status["needs_update"] is True+ def test_unusable_db_file_is_not_available(self, tmp_data_dir):+ """A ``journal_quality.db`` that exists but fails the validity+ probe (not a real SQLite file, no snapshot either) must not+ report ``available: True``. Bare existence previously let this+ through — every actual read would then rebuild (or, under a+ forbidding egress scope, refuse) instead of serving it, so the+ dashboard's install banner never appeared behind a file that+ answered with silent zeros.+ """+ (tmp_data_dir / DB_FILENAME).write_text("not a database")+ status = get_journal_data_status()+ assert status["available"] is False++ def test_valid_db_file_is_available(self, tmp_data_dir):+ """A genuinely valid compiled DB is available even with no+ snapshot on disk — the dashboard can still query it directly.+ """+ _write_valid_db(tmp_data_dir / DB_FILENAME)+ status = get_journal_data_status()+ assert status["available"] is True+class TestDownloadJournalData:def test_already_up_to_date(self, tmp_data_dir):@@ -403,3 +441,55 @@ class TestEnsureJournalDataCache:second = ensure_journal_data(auto_download=True)assert second == (None, False)assert mock_dl.call_count == 1++ def test_refusal_does_not_poison_a_later_allowed_call(self, tmp_data_dir):+ """A refused call must not answer the next caller that IS allowed.++ ``_ensure_cache`` stores only ``(timestamp, (dir, available))``+ — no trace of WHICH question it answered. A caller that is not+ permitted to download (test mock mode, or a lazy build whose+ egress scope forbids the public fetch) therefore must not write+ it: the entry would answer every+ ``ensure_journal_data(auto_download=True)`` for the rest of the+ 30 s TTL — another user's search, whose scope permits the fetch+ — with a stale "unavailable", silently suppressing a legitimate+ download.++ Revert the ``if not auto_download`` early return to a spelling+ that caches ``(None, False)`` and the second call here returns+ that cached tuple instead of downloading: ``mock_dl.call_count``+ stays 0 and the assertion below fails. Nothing is lost by not+ caching — the refusal did a single ``stat``, not the+ download/sentinel race the cache exists to absorb (the herd test+ above still pins that).+ """+ import local_deep_research.journal_quality.downloader as dl++ # The cache is module state and is not in conftest's+ # reset_all_singletons; clear it on both sides so neither a+ # previous test nor this one leaks a decision.+ dl._ensure_cache = None+ try:+ with patch.object(dl, "download_journal_data") as mock_dl:+ mock_dl.return_value = (True, "fetched")++ # tmp_data_dir has no openalex_sources.json.gz, so this+ # reaches the refusal branch rather than the cheap+ # "already present" early return.+ refused = ensure_journal_data(auto_download=False)+ assert refused == (None, False)+ assert mock_dl.call_count == 0, (+ "a refusal must not download anything itself"+ )++ # Immediately afterwards — well inside the 30 s TTL.+ allowed = ensure_journal_data(auto_download=True)++ assert mock_dl.call_count == 1, (+ "the refusal poisoned the shared availability cache: "+ "a caller that WAS allowed to download got the "+ "refusal's cached 'unavailable' instead"+ )+ assert allowed == (tmp_data_dir, True)+ finally:+ dl._ensure_cache = Nonediff --git a/tests/js/pages/journal-quality-runtime.test.js b/tests/js/pages/journal-quality-runtime.test.jsindex 864d052ab9..9e4d8cc865 100644--- a/tests/js/pages/journal-quality-runtime.test.js+++ b/tests/js/pages/journal-quality-runtime.test.js@@ -658,6 +658,102 @@ it('uses the research-scoped journal endpoint and renders its success shape', asexpect(renderYrTable).toHaveBeenCalledWith(journals);});+it('renders an em dash for the reference count when the reference DB was withheld', async () => {+ window.history.replaceState({}, '', '/metrics/journals?research_id=run%2Fa');+ document.body.innerHTML = `+ <div id="ldr-yr-loading" style="display: block"></div>+ <div id="ldr-yr-empty" style="display: none"></div>+ <div id="ldr-yr-content" style="display: none"></div>+ <span id="yr-stat-journals"></span>+ <span id="yr-stat-avg-quality"></span>+ <span id="yr-stat-papers"></span>+ <span id="yr-stat-predatory"></span>+ <span id="yr-table-count"></span>+ `;+ const journals = [{ name: 'Journal A' }];+ const fetchMock = vi.fn().mockResolvedValue({+ json: vi.fn().mockResolvedValue({+ status: 'success',+ // total_journals > 0 so the empty-state return above the+ // predatory-count line does not short-circuit rendering.+ summary: {+ total_journals: 1,+ avg_quality: 8.5,+ total_papers: 4,+ predatory_blocked: 0,+ },+ quality_distribution: { 8: 1 },+ journals,+ reference_data_available: false,+ }),+ });+ vi.stubGlobal('fetch', fetchMock);+ const harness = compileTemplateHarness({+ templatePath: TEMPLATE_PATH,+ functionNames: ['loadUserResearchJournals'],+ dependencies: {+ renderYrQualityChart: vi.fn(),+ renderYrSourceChart: vi.fn(),+ renderYrTable: vi.fn(),+ },+ returnExpression: '({ loadUserResearchJournals })',+ });++ await harness.loadUserResearchJournals();++ // `predatory_blocked: 0` must not read as "no predatory journals+ // found" when the reference DB was never actually consulted.+ expect(document.getElementById('yr-stat-predatory').textContent)+ .toBe('—');+});++it('renders the real count when the reference DB was explicitly available', async () => {+ window.history.replaceState({}, '', '/metrics/journals?research_id=run%2Fa');+ document.body.innerHTML = `+ <div id="ldr-yr-loading" style="display: block"></div>+ <div id="ldr-yr-empty" style="display: none"></div>+ <div id="ldr-yr-content" style="display: none"></div>+ <span id="yr-stat-journals"></span>+ <span id="yr-stat-avg-quality"></span>+ <span id="yr-stat-papers"></span>+ <span id="yr-stat-predatory"></span>+ <span id="yr-table-count"></span>+ `;+ const journals = [{ name: 'Journal A' }];+ const fetchMock = vi.fn().mockResolvedValue({+ json: vi.fn().mockResolvedValue({+ status: 'success',+ summary: {+ total_journals: 1,+ avg_quality: 8.5,+ total_papers: 4,+ predatory_blocked: 3,+ },+ quality_distribution: { 8: 1 },+ journals,+ // Explicit `true`, distinct from an older payload that omits+ // the field entirely (covered by the success-shape test+ // above) — both must render the real count, not the dash.+ reference_data_available: true,+ }),+ });+ vi.stubGlobal('fetch', fetchMock);+ const harness = compileTemplateHarness({+ templatePath: TEMPLATE_PATH,+ functionNames: ['loadUserResearchJournals'],+ dependencies: {+ renderYrQualityChart: vi.fn(),+ renderYrSourceChart: vi.fn(),+ renderYrTable: vi.fn(),+ },+ returnExpression: '({ loadUserResearchJournals })',+ });++ await harness.loadUserResearchJournals();++ expect(document.getElementById('yr-stat-predatory').textContent).toBe('3');+});+it('uses the aggregate journal endpoint and renders its empty success shape', async () => {window.history.replaceState({}, '', '/metrics/journals');document.body.innerHTML = `diff --git a/tests/security/test_journal_lazy_build_egress_gate.py b/tests/security/test_journal_lazy_build_egress_gate.pynew file mode 100644index 0000000000..ff3294ac61--- /dev/null+++ b/tests/security/test_journal_lazy_build_egress_gate.py@@ -0,0 +1,806 @@+"""The journal-data fetch must honour the user's egress scope everywhere.++Three entry points can pull the journal-quality datasets (OpenAlex / DOAJ+/ GitHub, hundreds of MB):++* the dashboard download button (``metrics.py``), which refuses with 403+ under PRIVATE_ONLY / STRICT;+* the reputation filter's background fetch thread, skipped under those+ scopes (``_should_skip_journal_fetch_for_scope``, pinned by+ ``test_egress_pep_coverage.py``); and+* the lazy build — ``JournalQualityDB._build_or_raise`` runs implicitly+ on any read through ``_ensure_engine`` when the DB file is missing or+ fails validation, and used to decide on test mock mode alone.++The lazy build is reached from two directions, and each needs its own+gate because each sees a different signal:++* inside a research run, on a worker thread that arms the run's egress+ context: ``_build_or_raise`` reads that context and turns the network+ download off (a local build from already-present snapshots still+ proceeds — only the network is off the table); and+* from the dashboard read routes, which Starlette runs on anyio+ threadpool workers where NO context is armed, leaving the context gate+ structurally blind. Those routes resolve the scope a research+ run for the user would get — the stored ``policy.egress_scope`` with+ ADAPTIVE resolved against the user's primary engine, as the worker and+ the reputation filter resolve it — and answer "unavailable" rather than let a page load DOWNLOAD the+ datasets.++The route gate answers the same question the build does, in the same+order, because the compiled DB is not the predicate that governs a+download — the snapshot is:++1. ``openalex_sources.json.gz`` on disk → the build compiles from disk+ and never asks the network. Allowed under every scope, including a+ forbidding one, which is the whole point: an offline rebuild must not+ darken the dashboard.+2. No snapshot, but the compiled DB exists AND passes the same validity+ probe ``_ensure_engine`` applies → no build runs. Allowed.+3. Neither → a read would have to download. Only here does the+ effective scope decide, and only here is the answer "unavailable".++Case 2 is not decoration: ``_ensure_engine`` rebuilds on a FAILED+validation as well as on a missing file, and three+``JOURNAL_QUALITY_SCHEMA_VERSION`` bumps have shipped, so every install+that upgrades past one takes that branch on its next read.++These tests pin both gates plus the two branches reachable only through+the first one: the ``policy_audit`` record and the scope-specific error.+"""++import sqlite3+from contextlib import contextmanager+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock, Mock, patch++import pytest+from fastapi.responses import JSONResponse+from starlette.requests import Request++from local_deep_research.journal_quality.db import (+ DB_FILENAME,+ JOURNAL_QUALITY_SCHEMA_VERSION,+ JournalQualityDB,+)+from local_deep_research.journal_quality.downloader import (+ REQUIRED_SNAPSHOT_FILENAME,+)+from local_deep_research.security.egress.audit_hook import (+ active_egress_context,+)+from local_deep_research.security.egress.policy import (+ EgressContext,+ EgressScope,+)+from local_deep_research.web.routers import metrics++_DB = "local_deep_research.journal_quality.db"+_TESTING = "local_deep_research.settings.env_definitions.testing"+_DOWNLOADER = "local_deep_research.journal_quality.downloader"+_PATHS = "local_deep_research.config.paths"+_DB_UTILS = "local_deep_research.utilities.db_utils"++#: The policy_audit record `_build_or_raise` writes when it refuses.+_AUDIT_LINE = "journal-data lazy build refused the network download"+#: Branch-specific substrings of two of `_build_or_raise`'s three+#: FileNotFoundError messages. All three share "not available", so an+#: unpinned `pytest.raises` passes on whichever branch happens to run.+_SCOPE_REFUSAL = "egress scope forbids the public download"+_GENERIC_FAILURE = "Check your network connection"+++def _ctx(scope: EgressScope) -> EgressContext:+ return EgressContext(+ scope=scope,+ primary_engine="library",+ require_local_llm=False,+ require_local_embeddings=False,+ )+++def _lazy_build_calls_with(recorder, *, message):+ """Run the lazy build in non-mock mode; return the auto_download kwarg.++ ``message`` pins which refusal branch raised.+ """+ with (+ patch(f"{_TESTING}.testing_with_mocks", return_value=False),+ patch(f"{_DOWNLOADER}.ensure_journal_data", recorder) as rec,+ ):+ db = __import__(+ "local_deep_research.journal_quality.db",+ fromlist=["JournalQualityDB"],+ ).JournalQualityDB()+ with pytest.raises(FileNotFoundError, match=message):+ db._build_or_raise(Path("/nonexistent/journal_quality.db"))+ assert rec.call_count == 1+ return rec.call_args.kwargs["auto_download"]+++def test_lazy_build_refuses_download_under_private_only(loguru_caplog_full):+ recorder = Mock(return_value=(None, False))++ with (+ loguru_caplog_full.at_level("INFO"),+ active_egress_context(_ctx(EgressScope.PRIVATE_ONLY)),+ ):+ auto_download = _lazy_build_calls_with(recorder, message=_SCOPE_REFUSAL)++ assert auto_download is False, (+ "lazy build attempted the public dataset download under a "+ "PRIVATE_ONLY egress scope — the scope forbids public fetches"+ )+ assert _AUDIT_LINE in loguru_caplog_full.text, (+ "a refused download must leave a policy_audit record"+ )+++def test_lazy_build_refuses_download_under_strict(loguru_caplog_full):+ recorder = Mock(return_value=(None, False))++ with (+ loguru_caplog_full.at_level("INFO"),+ active_egress_context(_ctx(EgressScope.STRICT)),+ ):+ auto_download = _lazy_build_calls_with(recorder, message=_SCOPE_REFUSAL)++ assert auto_download is False+ assert _AUDIT_LINE in loguru_caplog_full.text+++def test_lazy_build_without_active_context_still_downloads(+ loguru_caplog_full,+):+ """No active scope (a run whose snapshot failed to resolve, or a call+ from a thread that arms no context): this gate leaves the download+ alone, and nothing was refused, so no audit record is written."""+ recorder = Mock(return_value=(None, False))++ with loguru_caplog_full.at_level("INFO"):+ auto_download = _lazy_build_calls_with(+ recorder, message=_GENERIC_FAILURE+ )++ assert auto_download is True+ assert _AUDIT_LINE not in loguru_caplog_full.text+++def test_lazy_build_still_builds_locally_under_private_only(+ tmp_path, loguru_caplog_full+):+ """Snapshots already on disk: the local, network-free build proceeds+ even under a forbidding scope — only the network is off the table.+ Nothing was refused, so no policy record is due either."""+ recorder = Mock(return_value=(tmp_path, True))++ with (+ loguru_caplog_full.at_level("INFO"),+ active_egress_context(_ctx(EgressScope.PRIVATE_ONLY)),+ patch(f"{_TESTING}.testing_with_mocks", return_value=False),+ patch(f"{_DOWNLOADER}.ensure_journal_data", recorder),+ patch(f"{_DB}.build_db") as build,+ ):+ db = __import__(+ "local_deep_research.journal_quality.db",+ fromlist=["JournalQualityDB"],+ ).JournalQualityDB()+ db._build_or_raise(tmp_path / "journal_quality.db")++ assert build.call_count == 1, "local build from snapshots must proceed"+ assert _AUDIT_LINE not in loguru_caplog_full.text, (+ "the local build was allowed — recording it as a refused download "+ "would put a phantom entry in the policy audit trail"+ )+++# ===========================================================================+# The dashboard read routes: a page load must not start the download+# ===========================================================================++#: Every route in `web/routers/metrics.py` that reaches `_ensure_engine`+#: (and through it `_build_or_raise`): `/api/journals` via `ref.available`,+#: the two paper-rooted routes via `_get_ref_db_or_none` ->+#: `lookup_sources_batch` / `count_predatory_by_names`.+_READ_ROUTES = ("journals", "user-research", "per-research")+++def _request() -> Request:+ """A real Starlette Request — slowapi's decorator rejects a Mock."""+ return Request(+ {+ "type": "http",+ "method": "GET",+ "path": "/metrics/api/journals",+ "headers": [],+ "query_string": b"",+ "client": ("127.0.0.1", 1),+ "server": ("test", 80),+ "scheme": "http",+ }+ )+++def _call(route: str):+ if route == "journals":+ return metrics.api_journal_quality(_request(), username="alice")+ if route == "user-research":+ return metrics.api_user_research_journals(_request(), username="alice")+ return metrics.api_research_journals(+ _request(), "research-1", username="alice"+ )+++def _settings_manager(scope: str, primary: str | None = "arxiv") -> Mock:+ """A settings manager whose stored scope is ``scope``.++ Answers both reads: ``get_setting`` (the download button's literal+ scope) and ``get_settings_snapshot`` (the read-route gate, which+ resolves ADAPTIVE against ``search.tool`` the way a research run+ does). ``primary`` defaults to a public engine so a literal scope+ behaves as itself; ``None`` leaves ``search.tool`` out entirely.+ """+ manager = Mock()+ manager.get_setting.return_value = scope+ snapshot = {"policy.egress_scope": scope}+ if primary is not None:+ snapshot["search.tool"] = primary+ manager.get_settings_snapshot.return_value = snapshot+ return manager+++@contextmanager+def _dashboard(*, scope: str, data_dir: Path):+ """A dashboard request for a user whose persisted scope is ``scope``.++ ``data_dir`` stands in for the journal data directory, so what the+ machine happens to have on disk never decides these tests.++ ``_build_or_raise`` is stubbed because it is the assertion target:+ whether the read reached the build. ``download_journal_data`` is+ stubbed only as a backstop — with the build stubbed it is+ unreachable, so asserting on it here would be vacuous. The+ non-vacuous downloader evidence is+ ``test_forbidding_scope_is_what_stops_the_download``, which leaves+ ``_build_or_raise`` real.+ """+ manager = _settings_manager(scope)+ with (+ patch(f"{_DB_UTILS}.get_settings_manager", return_value=manager),+ patch(f"{_PATHS}.get_journal_data_directory", return_value=data_dir),+ patch(f"{_DB}.JournalQualityDB._build_or_raise") as build,+ patch(f"{_DOWNLOADER}.download_journal_data") as download,+ patch.object(+ metrics, "_get_ref_db_or_none", return_value=None+ ) as ref_db_getter,+ ):+ yield SimpleNamespace(+ build=build, download=download, ref_db_getter=ref_db_getter+ )+++@contextmanager+def _one_paper_row():+ """A user DB with one Paper row, so the paper-rooted routes get past+ their ``if not rows`` early return and reach the reference DB."""+ row = SimpleNamespace(+ container_title="Journal A",+ paper_count=2,+ year_min=2020,+ year_max=2024,+ )+ query = MagicMock()+ for method in ("filter", "join", "group_by", "order_by", "limit"):+ getattr(query, method).return_value = query+ query.all.return_value = [row]+ query.first.return_value = SimpleNamespace(id="research-1")+ session = MagicMock(bind=MagicMock())+ session.query.return_value = query+ inspector = MagicMock()+ inspector.has_table.return_value = True++ @contextmanager+ def open_session(*_args):+ yield session++ with (+ patch.object(metrics, "get_user_db_session", side_effect=open_session),+ patch("sqlalchemy.inspect", return_value=inspector),+ patch.object(metrics, "_lookup_journal_llm_quality", return_value={}),+ ):+ yield+++@contextmanager+def _stub_reference_db():+ """Reference DB stub for the cases where the read IS allowed through:+ the assertion is that the route got there, not what it read."""+ ref = MagicMock(available=True)+ ref.get_journals_page.return_value = ([{"name": "Journal A"}], 1)+ with patch(f"{_DB}.get_journal_reference_db", return_value=ref):+ yield ref+++def _assert_reached_the_reference_db(route, env, result, ref):+ if route == "journals":+ assert result["status"] == "success"+ ref.get_journals_page.assert_called_once()+ else:+ assert result["status"] == "success"+ env.ref_db_getter.assert_called_once_with()++[email protected]("scope", ["private_only", "strict"])[email protected]("route", _READ_ROUTES)+def test_dashboard_read_does_not_build_under_a_forbidding_scope(+ tmp_path, route, scope+):+ """A dashboard page load must not become a public dataset download.++ The reference DB is missing, so every one of these reads would run+ the lazy build, and `_build_or_raise`'s own gate cannot see this+ user's scope from a threadpool worker (no context is armed there).+ Remove the route-level gate and the read reaches `_build_or_raise`+ with `auto_download=True`: `env.build` records the call.+ """+ with _dashboard(scope=scope, data_dir=tmp_path) as env, _one_paper_row():+ result = _call(route)++ env.build.assert_not_called()+ if route == "journals":+ assert isinstance(result, JSONResponse)+ assert result.status_code == 503, (+ "the route must answer with its existing 'reference database "+ "not available' response, not build the database"+ )+ else:+ env.ref_db_getter.assert_not_called()+ assert result["status"] == "success"+ assert result["summary"]["predatory_blocked"] == 0++[email protected]("route", _READ_ROUTES)+def test_dashboard_read_proceeds_when_the_db_file_exists(tmp_path, route):+ """An existing file is read, never built, so no download can follow:+ a forbidding scope must not degrade the dashboard. Gating on the+ scope alone (ignoring the file) turns this into the 503 / empty+ response above."""+ (tmp_path / "journal_quality.db").touch()++ with (+ _dashboard(scope="private_only", data_dir=tmp_path) as env,+ _one_paper_row(),+ _stub_reference_db() as ref,+ ):+ result = _call(route)++ _assert_reached_the_reference_db(route, env, result, ref)++[email protected]("route", _READ_ROUTES)+def test_dashboard_read_is_unchanged_under_a_public_scope(tmp_path, route):+ """Positive control: with no DB file at all, a scope that permits+ public egress still reaches the reference DB (and, in production,+ still builds it). Without this, "always answer unavailable" would+ pass every other test in this section."""+ with (+ _dashboard(scope="public_only", data_dir=tmp_path) as env,+ _one_paper_row(),+ _stub_reference_db() as ref,+ ):+ result = _call(route)++ _assert_reached_the_reference_db(route, env, result, ref)+++# ===========================================================================+# What the gate actually predicts: the snapshot, not the compiled DB+# ===========================================================================+++def _write_snapshot(data_dir: Path) -> None:+ """Put the one REQUIRED snapshot on disk.++ Content is irrelevant here: ``ensure_journal_data`` decides on+ ``(user_dir / REQUIRED_SNAPSHOT_FILENAME).exists()`` alone and+ returns "available" without a single request, so the build that+ follows is local. Only the presence of the name matters.+ """+ (data_dir / REQUIRED_SNAPSHOT_FILENAME).write_bytes(b"")+++def _write_stale_schema_db(path: Path) -> None:+ """A real SQLite file stamped with a schema version this build rejects.++ Not an exotic corner: ``JOURNAL_QUALITY_SCHEMA_VERSION`` has been+ bumped three times (1→2, 2→3, 3→4), and every install that upgrades+ past a bump finds exactly this file — valid SQLite, wrong stamp — on+ its next read, which sends ``_ensure_engine`` into ``_build_or_raise``.+ """+ conn = sqlite3.connect(str(path))+ try:+ conn.execute(+ "PRAGMA user_version = %d" % (JOURNAL_QUALITY_SCHEMA_VERSION + 1)+ )+ conn.execute("CREATE TABLE t (x)")+ conn.commit()+ finally:+ conn.close()+++def _write_valid_db(path: Path) -> None:+ conn = sqlite3.connect(str(path))+ try:+ conn.execute(+ "PRAGMA user_version = %d" % JOURNAL_QUALITY_SCHEMA_VERSION+ )+ conn.execute("CREATE TABLE t (x)")+ conn.commit()+ finally:+ conn.close()+++def _write_corrupt_db(path: Path) -> None:+ path.write_text("this is not a database at all", encoding="utf-8")+++_DB_STATES = {+ "missing": lambda path: None,+ "valid": _write_valid_db,+ "stale_schema": _write_stale_schema_db,+ "corrupt": _write_corrupt_db,+}+++@contextmanager+def _gate_env(data_dir: Path, *, scope: str, primary: str | None = "arxiv"):+ """Point the gate at ``data_dir`` with ``scope`` as the stored value+ and ``primary`` as the user's ``search.tool``."""+ manager = _settings_manager(scope, primary)+ with (+ patch(f"{_PATHS}.get_journal_data_directory", return_value=data_dir),+ patch(f"{_DB_UTILS}.get_settings_manager", return_value=manager),+ ):+ yield+++ ("snapshot", "db_state", "scope", "expected_blocked"),+ [+ # Nothing on disk: the read would download, so the scope decides.+ (False, "missing", "private_only", True),+ (False, "missing", "strict", True),+ (False, "missing", "public_only", False),+ # ADAPTIVE (the default) with a public primary resolves+ # PUBLIC_ONLY. The private-primary half is+ # test_gate_resolves_adaptive_against_the_primary_engine.+ (False, "missing", "adaptive", False),+ # Unparseable stored value still fails closed.+ (False, "missing", "not-a-scope", True),+ # The file exists but `_ensure_engine` would REBUILD it. Gating on+ # `.exists()` alone answers "not blocked" here and lets a schema+ # bump turn one dashboard page load into the full download.+ (False, "stale_schema", "private_only", True),+ (False, "corrupt", "private_only", True),+ (False, "stale_schema", "public_only", False),+ # A valid file is read, never rebuilt: no build, no download.+ (False, "valid", "private_only", False),+ # Snapshot on disk: any build compiles from it, offline. Blocking+ # these would darken the dashboard of the very users this gate+ # exists to protect, for no egress benefit.+ (True, "missing", "private_only", False),+ (True, "stale_schema", "private_only", False),+ (True, "corrupt", "strict", False),+ (True, "valid", "private_only", False),+ ],+)+def test_gate_predicts_a_download_not_a_missing_file(+ tmp_path, snapshot, db_state, scope, expected_blocked+):+ """The gate must answer "would this read DOWNLOAD?", not "is the file+ there?".++ The two questions differ in both directions, and each direction is a+ real defect: a stale-schema file is "there" but rebuilds (and, with+ no snapshot, downloads), while a missing file with the snapshot+ beside it never touches the network.+ """+ if snapshot:+ _write_snapshot(tmp_path)+ _DB_STATES[db_state](tmp_path / DB_FILENAME)++ with _gate_env(tmp_path, scope=scope):+ blocked = metrics._journal_ref_db_read_would_download("alice")++ assert blocked is expected_blocked+++ ("scope", "primary", "expected_blocked"),+ [+ # A public primary: ADAPTIVE resolves PUBLIC_ONLY -> allowed.+ ("adaptive", "arxiv", False),+ ("adaptive", "searxng", False),+ # A private primary: ADAPTIVE resolves PRIVATE_ONLY, exactly as+ # the research worker's armed context and the reputation filter's+ # `_should_skip_journal_fetch_for_scope` resolve it. Gating on the+ # literal stored "adaptive" let a dashboard page load start the+ # download those two refuse.+ ("adaptive", "library", True),+ ("adaptive", "collection_abc", True),+ # No primary engine: the scope cannot be resolved -> fail closed,+ # like the worker, which refuses such a run.+ ("adaptive", None, True),+ ("public_only", None, True),+ ],+)+def test_gate_resolves_adaptive_against_the_primary_engine(+ tmp_path, scope, primary, expected_blocked+):+ """The read-route gate must see the scope a run would see, not the+ literal stored value."""+ with _gate_env(tmp_path, scope=scope, primary=primary):+ blocked = metrics._journal_ref_db_read_would_download("alice")++ assert blocked is expected_blocked+++def test_gate_fails_closed_when_settings_cannot_be_read(tmp_path):+ """A strict snapshot read that raises (SQLCipher session unusable)+ must answer "blocked", not fall back to a permissive default."""+ manager = _settings_manager("public_only")+ manager.get_settings_snapshot.side_effect = RuntimeError("db locked")+ with (+ patch(f"{_PATHS}.get_journal_data_directory", return_value=tmp_path),+ patch(f"{_DB_UTILS}.get_settings_manager", return_value=manager),+ ):+ assert metrics._journal_ref_db_read_would_download("alice") is True+ manager.get_settings_snapshot.assert_called_once_with(strict=True)++[email protected]("db_state", ["stale_schema", "corrupt"])+def test_gate_probe_does_not_delete_the_users_database(tmp_path, db_state):+ """Asking the question must not destroy the answer.++ ``JournalQualityDB._validate_existing_db`` unlinks an unusable file+ as part of deciding it is unusable — correct for the build path,+ unacceptable on a read route, where a GET would silently delete the+ user's reference DB. The gate uses ``journal_db_file_is_valid``, the+ read-only half, so the file is still there afterwards.+ """+ db_path = tmp_path / DB_FILENAME+ _DB_STATES[db_state](db_path)++ with _gate_env(tmp_path, scope="private_only"):+ assert metrics._journal_ref_db_read_would_download("alice") is True++ assert db_path.exists(), (+ "the read-route gate deleted the user's reference DB as a side "+ "effect of probing it"+ )++[email protected]("db_state", ["missing", "stale_schema"])+def test_snapshot_present_lets_the_read_reach_the_local_build(+ tmp_path, db_state+):+ """The permissive half of the gate, pinned against the build itself.++ With the snapshot on disk the gate says "not blocked" — and the read+ it lets through really does run the build. That build is local:+ ``ensure_journal_data`` returns "available" on the snapshot without a+ request (``test_lazy_build_still_builds_locally_under_private_only``+ pins that end). Gate and build have to agree, or the gate is either+ blocking an offline rebuild or waving through a download.+ """+ _write_snapshot(tmp_path)+ _DB_STATES[db_state](tmp_path / DB_FILENAME)++ with (+ _gate_env(tmp_path, scope="private_only"),+ patch(f"{_DB}.JournalQualityDB._build_or_raise") as build,+ ):+ assert metrics._journal_ref_db_read_would_download("alice") is False+ # A FRESH instance, never the module singleton: a leaked engine+ # would short-circuit `_ensure_engine` and hide the call.+ JournalQualityDB()._ensure_engine()++ assert build.call_count == 1, (+ "the read the gate allowed did not reach the build — the local "+ "rebuild from present snapshots is not happening"+ )++[email protected]("route", _READ_ROUTES)+def test_invalid_db_without_snapshot_is_treated_as_missing(tmp_path, route):+ """The upgrade path this gate exists for.++ Schema bump + snapshots deleted (a configuration+ ``get_journal_data_status`` explicitly supports: "The compiled DB is+ useful even when the source JSON has been deleted") + a forbidding+ scope. Gating on ``.exists()`` answers "not blocked" here and a+ dashboard page load starts the several-hundred-MB fetch.+ """+ _write_stale_schema_db(tmp_path / DB_FILENAME)++ with _dashboard(scope="private_only", data_dir=tmp_path) as env:+ with _one_paper_row():+ result = _call(route)++ env.build.assert_not_called()+ if route == "journals":+ assert isinstance(result, JSONResponse)+ assert result.status_code == 503+ else:+ env.ref_db_getter.assert_not_called()+ assert result["status"] == "success"+ assert result["reference_data_available"] is False++[email protected]("db_state", ["missing", "stale_schema"])[email protected]("route", _READ_ROUTES)+def test_snapshot_present_read_proceeds_under_a_forbidding_scope(+ tmp_path, route, db_state+):+ """Both of the limits the previous shape of this gate carried.++ ``db_state="missing"`` is a forbidding-scope user who has the+ snapshots but no compiled DB: the old gate answered "unavailable"+ where a purely local build was available.+ ``db_state="stale_schema"`` is the same user after an upgrade. Under+ both, the read proceeds.+ """+ _write_snapshot(tmp_path)+ _DB_STATES[db_state](tmp_path / DB_FILENAME)++ with (+ _dashboard(scope="private_only", data_dir=tmp_path) as env,+ _one_paper_row(),+ _stub_reference_db() as ref,+ ):+ result = _call(route)++ _assert_reached_the_reference_db(route, env, result, ref)+++def test_forbidding_scope_is_what_stops_the_download(tmp_path):+ """The discriminating pair, with the real ``_build_or_raise``.++ Every other route test in this module stubs ``_build_or_raise``, the+ only production path from these routes to ``download_journal_data``,+ which makes any "the downloader was not called" assertion there+ vacuous. Here the build is REAL and only the downloader itself is+ stubbed, so the two halves differ in exactly one thing — the+ persisted scope — and only one of them reaches the network call.++ Both halves end in a 503 (the permitted half's stubbed download+ "fails"), so the 503 proves nothing on its own; the call count is+ the whole evidence.+ """+ import local_deep_research.journal_quality.downloader as dl++ def run(scope: str) -> int:+ manager = _settings_manager(scope)+ # Not in conftest's reset_all_singletons: a negative entry from+ # the first half would answer the second half from cache and+ # never call the downloader at all.+ dl._ensure_cache = None+ with (+ patch(f"{_DB_UTILS}.get_settings_manager", return_value=manager),+ patch(+ f"{_PATHS}.get_journal_data_directory", return_value=tmp_path+ ),+ patch(f"{_TESTING}.testing_with_mocks", return_value=False),+ # A fresh instance, so `_ensure_engine` cannot be satisfied+ # by an engine another test left on the module singleton.+ patch(+ f"{_DB}.get_journal_reference_db",+ return_value=JournalQualityDB(),+ ),+ patch(+ f"{_DOWNLOADER}.download_journal_data",+ return_value=(+ False,+ "stubbed: this test never uses the network",+ ),+ ) as download,+ ):+ result = metrics.api_journal_quality(_request(), username="alice")+ assert isinstance(result, JSONResponse)+ assert result.status_code == 503+ return download.call_count++ try:+ # tmp_path has neither the snapshot nor a compiled DB, so a read+ # that gets past the gate has nothing local to build from.+ assert run("private_only") == 0, (+ "a dashboard page load under a scope that forbids public "+ "egress reached download_journal_data"+ )+ assert run("public_only") == 1, (+ "positive control: with no snapshot and no DB, a permitted "+ "scope must still reach the downloader — otherwise 'never "+ "download' would pass the assertion above for free"+ )+ finally:+ dl._ensure_cache = None++[email protected]("route", ("user-research", "per-research"))+def test_withheld_reference_db_is_flagged_in_the_response(tmp_path, route):+ """``predatory_blocked: 0`` must not read as a clean bill of health.++ With the reference DB withheld, these routes answer ``status:+ success`` and ``predatory_blocked: 0`` — a count of nothing that was+ never counted. The route's own comment calls silently undercounting+ predatory journals a no-fallbacks violation, so the response says+ which it is.+ """+ with _dashboard(scope="private_only", data_dir=tmp_path) as env:+ with _one_paper_row():+ withheld = _call(route)++ env.ref_db_getter.assert_not_called()+ assert withheld["summary"]["predatory_blocked"] == 0+ assert withheld["reference_data_available"] is False++ # Same user, same zero count, but the reference DB was consulted.+ # A 0-byte file passes the validity probe (user_version 0 is+ # grandfathered), so the gate lets the read through.+ (tmp_path / DB_FILENAME).touch()+ ref = MagicMock()+ ref.lookup_sources_batch.return_value = {}+ ref.count_predatory_by_names.return_value = 0+ with (+ _dashboard(scope="private_only", data_dir=tmp_path),+ _one_paper_row(),+ # `_dashboard` stubs `_get_ref_db_or_none` to None; hand these+ # routes a reference DB that is actually there instead.+ patch.object(metrics, "_get_ref_db_or_none", return_value=ref),+ ):+ available = _call(route)++ assert available["summary"]["predatory_blocked"] == 0+ assert available["reference_data_available"] is True, (+ "the flag must distinguish 'checked, found none' from 'never "+ "checked' — both report predatory_blocked: 0"+ )++[email protected]("route", ("user-research", "per-research"))+def test_failed_lazy_build_is_flagged_in_the_response(tmp_path, route):+ """A reference DB that could not be built is "not checked" too.++ Under a permitting scope the gate lets the read through, and+ ``_get_ref_db_or_none`` hands back the singleton without opening+ anything. When the lazy build then fails — no snapshot and the+ network down, say — the lookups swallow the ``FileNotFoundError``+ into ``{}`` / ``0``. Keying the flag on the handle being non-None+ reported that as ``reference_data_available: true`` with+ ``predatory_blocked: 0``: the "checked, found none" reading the flag+ exists to rule out.+ """+ from local_deep_research.journal_quality.db import JournalQualityDB++ ref = JournalQualityDB()+ with (+ _dashboard(scope="public_only", data_dir=tmp_path),+ _one_paper_row(),+ patch(+ f"{_DB}.JournalQualityDB._build_or_raise",+ side_effect=FileNotFoundError(+ "Journal data files not available. Check your network "+ "connection or download manually from the dashboard."+ ),+ ) as build,+ patch.object(metrics, "_get_ref_db_or_none", return_value=ref),+ ):+ result = _call(route)++ build.assert_called() # the read really reached the failing build+ assert result["status"] == "success"+ assert result["summary"]["predatory_blocked"] == 0+ assert result["reference_data_available"] is False, (+ "a reference DB whose lazy build failed was reported as checked"+ )