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(cache): cache key provenance hardening for library document keys (#8087)

LearningCircuit570c280c1ef7
diff --git a/changelog.d/+library-cache-key-provenance.security.md b/changelog.d/+library-cache-key-provenance.security.md
new file mode 100644
index 0000000000..bb183b97da
--- /dev/null
+++ b/changelog.d/+library-cache-key-provenance.security.md
@@ -0,0 +1 @@
+Improve consistency when sharing library content through the research cache, and preserve active fetch coordination when the cache is cleared.
diff --git a/src/local_deep_research/advanced_search_system/tools/fetch/library_resolver.py b/src/local_deep_research/advanced_search_system/tools/fetch/library_resolver.py
index 23eda8c96b..cea6d3c494 100644
--- a/src/local_deep_research/advanced_search_system/tools/fetch/library_resolver.py
+++ b/src/local_deep_research/advanced_search_system/tools/fetch/library_resolver.py
@@ -268,16 +268,29 @@ def resolve_library_document(
the egress gate + budget + HTTP fetcher so accounting stays symmetric
(library reads are local and consume no network slot; web fetches do,
even on cache hits, preserving historical accounting).
+
+ Cache key provenance: the user check runs before any cache read, and
+ a cached entry is served only when it was written by a library DB read
+ path (this resolver or the library / collection engines). Any other
+ entry under a library key is ignored and the document is read from the
+ user's database instead.
"""
reference = _parse_library_reference(url)
if reference is None:
return None
+ lookup_value = reference.value
+ chunk_index = reference.chunk_index
+ document_chunk_id = reference.document_chunk_id
+
+ if not username:
+ # No user context → no library. Caller falls through to the
+ # egress policy, which rejects the URL as ``unsupported_scheme``.
+ return None
+
try:
- from ....utilities.research_content_cache import (
- resolve_cache as _resolve_cache,
- )
+ from ....utilities import research_content_cache as _rcc
- _cache = _resolve_cache(content_cache)
+ _cache = _rcc.resolve_cache(content_cache)
except Exception: # pragma: no cover - defensive
_cache = None
if _cache is not None:
@@ -285,7 +298,11 @@ def resolve_library_document(
_hit = _cache.get(url)
except Exception: # pragma: no cover - defensive
_hit = None
- if _hit is not None and isinstance(_hit.get("content"), str):
+ if (
+ _hit is not None
+ and _rcc.is_library_provenance_entry(_hit)
+ and isinstance(_hit.get("content"), str)
+ ):
_text = _hit["content"]
_title = _hit.get("title") or ""
_curl = _hit.get("url") or url
@@ -296,14 +313,6 @@ def resolve_library_document(
"snippet": (_text[:200].strip() if _text else _title or "")
or "",
}
- lookup_value = reference.value
- chunk_index = reference.chunk_index
- document_chunk_id = reference.document_chunk_id
-
- if not username:
- # No user context → no library. Caller falls through to the
- # egress policy, which rejects the URL as ``unsupported_scheme``.
- return None
# Lazy imports: avoid pulling SQLAlchemy / user-DB modules into the
# module-load path for the (common) no-library case.
@@ -463,6 +472,7 @@ def resolve_library_document(
text,
title=document.title or f"Document {lookup_value}",
url_out=citation_url,
+ provenance=_rcc.LIBRARY_PROVENANCE,
)
except Exception: # allow: silent-exception
pass
diff --git a/src/local_deep_research/utilities/research_content_cache.py b/src/local_deep_research/utilities/research_content_cache.py
index 985b75973f..e89a0937a1 100644
--- a/src/local_deep_research/utilities/research_content_cache.py
+++ b/src/local_deep_research/utilities/research_content_cache.py
@@ -120,6 +120,29 @@ def content_cache_key(url: Any, collection_id: Any = None) -> str:
return f"raw:{stripped}"
+#: Provenance tag for entries written by the code paths that read the
+#: user's own library database (the library resolver and the library /
+#: collection search engines). Library-keyed entries without this tag are
+#: never served as the user's library document.
+LIBRARY_PROVENANCE = "library"
+
+
+def is_library_cache_key(url: Any) -> bool:
+ """Whether *url* maps to a library (``lib:``) cache key."""
+ try:
+ return content_cache_key(url).startswith("lib:")
+ except Exception: # pragma: no cover - defensive
+ return False
+
+
+def is_library_provenance_entry(entry: Any) -> bool:
+ """Whether a cache *entry* was written by a library DB read path."""
+ return (
+ isinstance(entry, dict)
+ and entry.get("provenance") == LIBRARY_PROVENANCE
+ )
+
+
class ResearchContentCache:
"""Thread-safe in-memory store of fetched page / chunk text.
@@ -209,6 +232,7 @@ class ResearchContentCache:
author: str | None = None,
published_date: Any | None = None,
collection_id: Any = None,
+ provenance: str | None = None,
) -> None:
"""Store *content* for *url*, keeping the longest version on conflict.
@@ -222,16 +246,27 @@ class ResearchContentCache:
Library chunk URLs are namespaced by *collection_id* (see
:func:`content_cache_key`): the same chunk index can hold
different text per collection.
+
+ *provenance* records which path wrote the entry
+ (:data:`LIBRARY_PROVENANCE` for library DB reads). Provenance takes
+ precedence over length: a library-provenance entry is never
+ replaced by an untagged write, and a library-provenance write
+ always replaces an untagged entry under the same key.
"""
if not isinstance(content, str):
return
key = content_cache_key(url, collection_id)
+ new_is_library = provenance == LIBRARY_PROVENANCE
with self._lock:
existing = self._entries.get(key)
- if existing is not None and len(existing.get("content", "")) >= len(
- content
- ):
- return
+ if existing is not None:
+ old_is_library = is_library_provenance_entry(existing)
+ if old_is_library and not new_is_library:
+ return
+ if old_is_library == new_is_library and len(
+ existing.get("content", "")
+ ) >= len(content):
+ return
if existing is not None:
self._total_bytes -= len(existing.get("content", "") or "")
# Re-insert as newest so FIFO eviction drops truly old URLs.
@@ -245,6 +280,8 @@ class ResearchContentCache:
entry["author"] = author
if published_date is not None:
entry["published_date"] = published_date
+ if provenance is not None:
+ entry["provenance"] = provenance
self._entries[key] = entry
self._total_bytes += len(content)
self._puts += 1
@@ -337,8 +374,14 @@ class ResearchContentCache:
# failures — or a later caller would block until wait_timeout
# on a dead event. Store-before-wake holds because put runs
# inside try before this finally signals the event.
+ #
+ # Release only our own claim: after ``clear()`` another caller
+ # may already own a fresh event under the same key, and an
+ # unconditional pop would drop that claim and let a third
+ # caller start a duplicate fetch.
with self._lock:
- self._inflight.pop(key, None)
+ if self._inflight.get(key) is event:
+ self._inflight.pop(key, None)
event.set()
# -- SSRF-verdict memo (per-run, defense-in-depth) ------------------
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_library.py b/src/local_deep_research/web_search_engines/engines/search_engine_library.py
index 9239e31e43..1bb2fc6643 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_library.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_library.py
@@ -48,6 +48,10 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
# Mark as local RAG engine for tool selection and safety checks
is_local = True
+ # Reads the user's own library DB, so it (and CollectionSearchEngine)
+ # may write shared research cache entries under library keys.
+ writes_library_cache_keys = True
+
# Egress (ADR-0007): a local document store — sensitive data, kept on-box.
egress_sensitivity = Sensitivity.SENSITIVE
egress_exposure = Exposure.CONTAINED
diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.py
index e77ac2b79b..1067a6c29b 100644
--- a/src/local_deep_research/web_search_engines/search_engine_base.py
+++ b/src/local_deep_research/web_search_engines/search_engine_base.py
@@ -35,6 +35,11 @@ from ..config.thread_settings import get_setting_from_snapshot
from ..security.log_sanitizer import sanitize_error_message, scrub_error
from ..security.egress.classification import Exposure, Sensitivity
from ..utilities.thread_context import clear_search_context, set_search_context
+from ..utilities.research_content_cache import (
+ LIBRARY_PROVENANCE as _LIBRARY_PROVENANCE,
+ is_library_cache_key as _is_library_cache_key,
+ is_library_provenance_entry as _is_library_provenance_entry,
+)
from .rate_limiting import RateLimitError, get_tracker
from .engine_availability import (
@@ -228,6 +233,13 @@ class BaseSearchEngine(ABC):
# Local engines search private document collections stored locally
is_local = False
+ # Cache key provenance: only engines that read the user's own library
+ # database (the library and collection RAG engines) may write shared
+ # research cache entries under library keys (``/library/document/...``).
+ # Every other engine's result links come from the engine's own data, so
+ # a library-shaped link there must not populate the library namespace.
+ writes_library_cache_keys = False
+
# Egress data classification (ADR-0007). Two orthogonal axes, declared
# explicitly per engine alongside is_public/is_local. The defaults fail
# closed: an engine that forgets to classify itself is treated as the most
@@ -998,6 +1010,11 @@ class BaseSearchEngine(ABC):
hit = cache.get(link)
except Exception: # pragma: no cover - defensive
hit = None
+ if hit is not None and _is_library_cache_key(link):
+ # Library keys are served only from entries written by a
+ # library DB read path; anything else is a miss here.
+ if not _is_library_provenance_entry(hit):
+ hit = None
if hit is not None and isinstance(hit.get("content"), str):
# A preview can already carry an abstract in full_content.
# The shared cache contains complete text and takes priority.
@@ -1026,10 +1043,16 @@ class BaseSearchEngine(ABC):
establishable collection are not stored under the shared URL key.
Entries this engine's grant would not allow to read are not
written either, keeping the shared cache grant-consistent.
+
+ Library keys (``/library/document/...``) are written only by
+ engines with ``writes_library_cache_keys`` (the library and
+ collection engines), tagged with library provenance. Other engines'
+ library-shaped links are not stored.
"""
cache = self.get_content_cache()
if cache is None or not items:
return
+ writes_library = bool(getattr(self, "writes_library_cache_keys", False))
for item in items:
if not isinstance(item, dict):
continue
@@ -1041,6 +1064,10 @@ class BaseSearchEngine(ABC):
continue
if not self._is_cache_url_allowed(link):
continue
+ is_library_key = _is_library_cache_key(link)
+ if is_library_key and not writes_library:
+ continue
+ provenance = _LIBRARY_PROVENANCE if is_library_key else None
try:
if self._is_library_chunk_link(link):
scope = self._collection_scope_for_item(item)
@@ -1052,6 +1079,7 @@ class BaseSearchEngine(ABC):
title=item.get("title"),
url_out=link,
collection_id=scope,
+ provenance=provenance,
)
else:
cache.put(
@@ -1059,6 +1087,7 @@ class BaseSearchEngine(ABC):
content,
title=item.get("title"),
url_out=link,
+ provenance=provenance,
)
except Exception: # pragma: no cover - defensive
continue
diff --git a/tests/utilities/test_research_cache_clear_handoff.py b/tests/utilities/test_research_cache_clear_handoff.py
new file mode 100644
index 0000000000..c733543d37
--- /dev/null
+++ b/tests/utilities/test_research_cache_clear_handoff.py
@@ -0,0 +1,87 @@
+"""Ownership handoff when a shared content cache is cleared mid-fetch."""
+
+from asyncio import CancelledError
+from concurrent.futures import ThreadPoolExecutor
+from threading import Event
+from unittest.mock import Mock
+
+import pytest
+
+from local_deep_research.utilities.research_content_cache import (
+ ResearchContentCache,
+ content_cache_key,
+)
+
+
[email protected]("first_outcome", ["empty", "exception", "cancelled"])
+def test_clear_keeps_the_actual_replacement_owner_and_waiter(
+ monkeypatch, first_outcome
+):
+ cache = ResearchContentCache()
+ url = "https://example.com/source"
+ key = content_cache_key(url)
+ first_started, release_first = Event(), Event()
+ second_started, release_second = Event(), Event()
+ waiter_started = Event()
+ unexpected_fetch = Mock(side_effect=AssertionError("duplicate fetch"))
+
+ def first_fetch():
+ first_started.set()
+ assert release_first.wait(10)
+ if first_outcome == "exception":
+ raise OSError("synthetic failure")
+ if first_outcome == "cancelled":
+ raise CancelledError("synthetic cancellation")
+ return
+
+ def second_fetch():
+ second_started.set()
+ assert release_second.wait(10)
+ return {"content": "replacement result"}
+
+ with ThreadPoolExecutor(max_workers=3) as executor:
+ first = executor.submit(cache.get_or_fetch, url, first_fetch)
+ try:
+ assert first_started.wait(5)
+ cache.clear()
+ second = executor.submit(cache.get_or_fetch, url, second_fetch)
+ assert second_started.wait(5)
+ with cache._lock:
+ second_event = cache._inflight[key]
+ release_first.set()
+ if first_outcome == "empty":
+ assert first.result(timeout=5) is None
+ else:
+ error = (
+ OSError if first_outcome == "exception" else CancelledError
+ )
+ with pytest.raises(error):
+ first.result(timeout=5)
+ assert cache._inflight.get(key) is second_event
+
+ real_wait = second_event.wait
+
+ def observe_wait(timeout=None):
+ waiter_started.set()
+ return real_wait(timeout)
+
+ monkeypatch.setattr(second_event, "wait", observe_wait)
+ waiter = executor.submit(
+ cache.get_or_fetch, url, unexpected_fetch, wait_timeout=5
+ )
+ assert waiter_started.wait(5)
+ assert not waiter.done()
+ unexpected_fetch.assert_not_called()
+ release_second.set()
+ assert second.result(timeout=5)["content"] == "replacement result"
+ assert waiter.result(timeout=5)["content"] == "replacement result"
+ finally:
+ release_first.set()
+ release_second.set()
+
+ unexpected_fetch.assert_not_called()
+ assert cache._inflight == {}
+ assert (
+ cache.get_or_fetch(url, unexpected_fetch)["content"]
+ == "replacement result"
+ )
diff --git a/tests/utilities/test_research_cache_key_provenance.py b/tests/utilities/test_research_cache_key_provenance.py
new file mode 100644
index 0000000000..ea6454540b
--- /dev/null
+++ b/tests/utilities/test_research_cache_key_provenance.py
@@ -0,0 +1,277 @@
+"""Cache key provenance hardening for the shared research content cache.
+
+Library keys (``/library/document/...``) in the run-wide cache are served
+as the user's own library documents, so only the code paths that read the
+user's library database may populate them:
+
+* engines other than the library / collection engines never write
+ library-keyed entries;
+* library-keyed entries are served only when tagged with library
+ provenance (the resolver and the engine fill path both check);
+* the resolver checks for a user before it consults the cache.
+
+Also pins the in-flight claim release in ``get_or_fetch``: after
+``clear()``, a finishing owner must not drop a newer owner's claim.
+"""
+
+from __future__ import annotations
+
+import threading
+from unittest.mock import MagicMock, patch
+
+from local_deep_research.utilities.research_content_cache import (
+ LIBRARY_PROVENANCE,
+ ResearchContentCache,
+ content_cache_key,
+ is_library_cache_key,
+)
+from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+)
+
+DOC_ID = "123e4567-e89b-12d3-a456-426614174000"
+DOC_URL = f"/library/document/{DOC_ID}"
+DB_TEXT = "text read from the user's library database"
+OTHER_TEXT = "text supplied by a non-library engine " * 20
+
+
+class _NonLibraryEngine(BaseSearchEngine):
+ def _get_previews(self, query):
+ return []
+
+ def _get_full_content(self, items):
+ return items
+
+
+class _LibraryEngine(_NonLibraryEngine):
+ writes_library_cache_keys = True
+
+
+def _complete_item(link, text):
+ return {
+ "link": link,
+ "title": "Some title",
+ "full_content": text,
+ "full_content_is_complete": True,
+ }
+
+
+def _patched_db(text=DB_TEXT):
+ """Patch the user DB session so the resolver reads *text*."""
+ from local_deep_research.database.models.library import Document
+
+ doc = MagicMock()
+ doc.id = DOC_ID
+ doc.title = "Library title"
+ doc.text_content = text
+
+ session = MagicMock()
+
+ def query_mock(model):
+ q = MagicMock()
+ if model == Document:
+ q.filter_by.return_value.first.return_value = doc
+ return q
+
+ session.query.side_effect = query_mock
+ session_cm = MagicMock()
+ session_cm.__enter__.return_value = session
+ session_cm.__exit__.return_value = False
+ return session, patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ return_value=session_cm,
+ )
+
+
+class TestEngineWriteProvenance:
+ def test_library_url_maps_to_library_key(self):
+ assert is_library_cache_key(DOC_URL) is True
+ assert is_library_cache_key("https://example.com/page") is False
+
+ def test_only_library_engines_may_write_library_keys(self):
+ from local_deep_research.web_search_engines.engines.search_engine_collection import (
+ CollectionSearchEngine,
+ )
+ from local_deep_research.web_search_engines.engines.search_engine_library import (
+ LibraryRAGSearchEngine,
+ )
+
+ assert BaseSearchEngine.writes_library_cache_keys is False
+ assert LibraryRAGSearchEngine.writes_library_cache_keys is True
+ assert CollectionSearchEngine.writes_library_cache_keys is True
+
+ def test_non_library_engine_does_not_write_library_key(self):
+ cache = ResearchContentCache()
+ engine = _NonLibraryEngine(content_cache=cache)
+ engine._store_full_content_in_cache(
+ [_complete_item(DOC_URL, OTHER_TEXT)]
+ )
+ assert cache.get(DOC_URL) is None
+
+ def test_non_library_engine_still_writes_web_keys(self):
+ cache = ResearchContentCache()
+ engine = _NonLibraryEngine(content_cache=cache)
+ engine._is_cache_url_allowed = lambda link: True
+ engine._store_full_content_in_cache(
+ [_complete_item("https://example.com/page", "web body")]
+ )
+ hit = cache.get("https://example.com/page")
+ assert hit is not None and hit["content"] == "web body"
+ assert "provenance" not in hit
+
+ def test_library_engine_writes_tagged_entry(self):
+ cache = ResearchContentCache()
+ engine = _LibraryEngine(content_cache=cache)
+ engine._store_full_content_in_cache([_complete_item(DOC_URL, DB_TEXT)])
+ hit = cache.get(DOC_URL)
+ assert hit is not None
+ assert hit["content"] == DB_TEXT
+ assert hit["provenance"] == LIBRARY_PROVENANCE
+
+ def test_non_library_result_not_served_as_library_document(self):
+ """End to end: a non-library engine result carrying a library link
+ must not become what the resolver returns for that document."""
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ library_resolver as lr,
+ )
+
+ cache = ResearchContentCache()
+ engine = _NonLibraryEngine(content_cache=cache)
+ engine._store_full_content_in_cache(
+ [_complete_item(DOC_URL, OTHER_TEXT)]
+ )
+ session, db_patch = _patched_db()
+ with db_patch:
+ result = lr.resolve_library_document(
+ DOC_URL, "someone", content_cache=cache
+ )
+ assert result is not None
+ assert result["content"] == DB_TEXT
+ assert session.query.call_count > 0
+
+ def test_engine_fill_ignores_untagged_library_entry(self):
+ cache = ResearchContentCache()
+ cache.put(DOC_URL, OTHER_TEXT, title="T", url_out=DOC_URL)
+ engine = _LibraryEngine(content_cache=cache)
+ items = [{"link": DOC_URL, "title": "T"}]
+ cached, missing = engine._fill_full_content_from_cache(items)
+ assert cached == []
+ assert missing == items
+ assert "full_content" not in items[0]
+
+
+class TestCachePutProvenance:
+ def test_untagged_write_does_not_replace_library_entry(self):
+ cache = ResearchContentCache()
+ cache.put(DOC_URL, DB_TEXT, provenance=LIBRARY_PROVENANCE)
+ cache.put(DOC_URL, OTHER_TEXT) # longer, but untagged
+ hit = cache.get(DOC_URL)
+ assert hit["content"] == DB_TEXT
+ assert hit["provenance"] == LIBRARY_PROVENANCE
+
+ def test_library_write_replaces_untagged_entry(self):
+ cache = ResearchContentCache()
+ cache.put(DOC_URL, OTHER_TEXT)
+ cache.put(DOC_URL, "short", provenance=LIBRARY_PROVENANCE)
+ hit = cache.get(DOC_URL)
+ assert hit["content"] == "short"
+ assert hit["provenance"] == LIBRARY_PROVENANCE
+
+ def test_longest_wins_within_same_provenance(self):
+ cache = ResearchContentCache()
+ cache.put(DOC_URL, "longer text", provenance=LIBRARY_PROVENANCE)
+ cache.put(DOC_URL, "short", provenance=LIBRARY_PROVENANCE)
+ assert cache.get(DOC_URL)["content"] == "longer text"
+
+
+class TestResolverProvenance:
+ def test_no_username_never_serves_cache(self):
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ library_resolver as lr,
+ )
+
+ cache = ResearchContentCache()
+ cache.put(
+ DOC_URL,
+ DB_TEXT,
+ title="T",
+ url_out=DOC_URL,
+ provenance=LIBRARY_PROVENANCE,
+ )
+ assert (
+ lr.resolve_library_document(DOC_URL, None, content_cache=cache)
+ is None
+ )
+ assert (
+ lr.resolve_library_document(DOC_URL, "", content_cache=cache)
+ is None
+ )
+
+ def test_untagged_entry_falls_through_to_db(self):
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ library_resolver as lr,
+ )
+
+ cache = ResearchContentCache()
+ cache.put(DOC_URL, OTHER_TEXT, title="T", url_out=DOC_URL)
+ session, db_patch = _patched_db()
+ with db_patch:
+ result = lr.resolve_library_document(
+ DOC_URL, "someone", content_cache=cache
+ )
+ assert result["content"] == DB_TEXT
+ assert session.query.call_count > 0
+ # The DB read replaces the untagged entry with a tagged one.
+ hit = cache.get(DOC_URL)
+ assert hit["content"] == DB_TEXT
+ assert hit["provenance"] == LIBRARY_PROVENANCE
+
+ def test_tagged_entry_served_without_db(self):
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ library_resolver as lr,
+ )
+
+ cache = ResearchContentCache()
+ cache.put(
+ DOC_URL,
+ DB_TEXT,
+ title="T",
+ url_out=DOC_URL,
+ provenance=LIBRARY_PROVENANCE,
+ )
+ session, db_patch = _patched_db(text="unused")
+ with db_patch:
+ result = lr.resolve_library_document(
+ DOC_URL, "someone", content_cache=cache
+ )
+ assert result["content"] == DB_TEXT
+ assert session.query.call_count == 0
+
+
+class TestInflightReleaseAfterClear:
+ def test_finishing_owner_keeps_newer_claim(self):
+ """After ``clear()`` a new owner may claim the same key; the old
+ owner's release must not remove that newer claim."""
+ cache = ResearchContentCache()
+ url = "https://example.com/race"
+ key = content_cache_key(url)
+ newer_claim = threading.Event()
+
+ def fetch():
+ cache.clear()
+ # A second caller elects itself owner of the cleared key.
+ with cache._lock:
+ assert key not in cache._inflight
+ cache._inflight[key] = newer_claim
+ return {"content": "body", "url": url}
+
+ result = cache.get_or_fetch(url, fetch)
+ assert result is not None and result["content"] == "body"
+ assert cache._inflight.get(key) is newer_claim
+ assert not newer_claim.is_set()
+
+ def test_owner_still_releases_own_claim(self):
+ cache = ResearchContentCache()
+ url = "https://example.com/own"
+ cache.get_or_fetch(url, lambda: {"content": "body", "url": url})
+ assert cache._inflight == {}
diff --git a/tests/utilities/test_research_content_cache.py b/tests/utilities/test_research_content_cache.py
index 00d117df7a..d599a96f9e 100644
--- a/tests/utilities/test_research_content_cache.py
+++ b/tests/utilities/test_research_content_cache.py
@@ -26,6 +26,7 @@ from unittest.mock import MagicMock, patch
import pytest
from local_deep_research.utilities.research_content_cache import (
+ LIBRARY_PROVENANCE,
ResearchContentCache,
bind_cache_to_research,
content_cache_key,
@@ -1099,6 +1100,7 @@ class TestLibraryResolverCache:
"cached doc text",
title="DocT",
url_out="/library/document/12345678123456781234567812345678",
+ provenance=LIBRARY_PROVENANCE,
)
result = lr.resolve_library_document(
"/library/document/12345678123456781234567812345678",
@@ -1139,6 +1141,7 @@ class TestLibraryResolverCache:
"cached",
title="T",
url_out="/library/document/12345678123456781234567812345678",
+ provenance=LIBRARY_PROVENANCE,
)
resolver = lr.make_library_resolver("someone", content_cache=cache)
assert (
@@ -1439,6 +1442,9 @@ class TestChunkCollectionScoping:
)
class CollEngine(BaseSearchEngine):
+ # Stands in for the collection engine, which may write library keys.
+ writes_library_cache_keys = True
+
def __init__(self, **kwargs):
super().__init__(search_snippets_only=False, **kwargs)
@@ -1692,7 +1698,13 @@ class TestGrantAwareCache:
cache = ResearchContentCache()
cache.put("https://example.com/pub", "public body", title="T")
doc = "/library/document/12345678123456781234567812345678"
- cache.put(doc, "doc text", title="D", url_out=doc)
+ cache.put(
+ doc,
+ "doc text",
+ title="D",
+ url_out=doc,
+ provenance=LIBRARY_PROVENANCE,
+ )
engine = StubEngine(content_cache=cache)
items = [
{"link": "https://example.com/pub", "title": "T"},
@@ -2644,7 +2656,9 @@ class TestReviewOptionalFollowups:
"search.tool": {"value": "arxiv"},
}
cache = ResearchContentCache()
- cache.put(self._DOC, "local body", title="T")
+ cache.put(
+ self._DOC, "local body", title="T", provenance=LIBRARY_PROVENANCE
+ )
cache.put("https://example.com/pub", "public body", title="T")
engine = self._stub_engine(cache, bogus_snapshot)
# Web still fails closed (matches the network path disabling fetch).
@@ -2789,7 +2803,9 @@ class TestReviewOptionalFollowups:
cache = ResearchContentCache()
public_url = "http://93.184.216.34/"
cache.put(public_url, "public body", title="T")
- cache.put(self._DOC, "local body", title="T")
+ cache.put(
+ self._DOC, "local body", title="T", provenance=LIBRARY_PROVENANCE
+ )
engine = self._stub_engine(cache, public_snapshot)
# Sanity: both servable before the cliff.
assert engine._is_cache_url_allowed(public_url) is True