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(fetch): resolve non-canonical library document URLs (#5392)

Ziyang Guo743d57f30582
diff --git a/changelog.d/+library-resolver-url-aliases.bugfix.md b/changelog.d/+library-resolver-url-aliases.bugfix.md
new file mode 100644
index 0000000000..ea0c366f3f
--- /dev/null
+++ b/changelog.d/+library-resolver-url-aliases.bugfix.md
@@ -0,0 +1 @@
+Resolve non-canonical local-library references emitted by research agents instead of sending them to the egress-denial path.
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 cbb2804633..d170295d31 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
@@ -6,7 +6,8 @@ strings that the egress policy correctly rejects as
not know how to fetch even without a policy gate):
1. **Local library document references** like
- ``/library/document/<uuid>`` or ``/library/document/<uuid>/pdf``.
+ ``/library/document/<uuid>``, ``/lib/document/<uuid>``,
+ ``https://library.document/<uuid>``, or ``[<uuid>]``.
The library RAG search engine and the collection search engine emit
these as the citation URL of a search hit (see
``web_search_engines.engines.search_engine_library.LibraryRAGSearchEngine.search``
@@ -30,17 +31,30 @@ generic "blocked by egress policy" denial that wastes a fetch slot
from __future__ import annotations
import re
+import uuid
+from dataclasses import dataclass
from typing import Any, Callable, Optional
+from urllib.parse import unquote, urlsplit
from loguru import logger
-# Match ``/library/document/<uuid>`` and ``/library/document/<uuid>/pdf``
-# (with optional trailing slash). The same regex is used by the download
-# service in ``research_library.services.download_service`` — keep them
-# in sync if either gains a new suffix.
+# Match canonical paths and the ``/lib/document/...`` abbreviation observed
+# in agent tool calls. The same suffix is used by download_service.
_LIBRARY_PATH_RE = re.compile(
- r"^/library/document/(?P<doc_id>[^/?#]+)(?:/(?P<suffix>pdf))?/?$"
+ r"^/(?:library|lib)/document/(?P<doc_id>[^/?#]+)"
+ r"(?:/(?P<suffix>pdf))?/?$"
+)
+_DOCUMENT_ID_PATTERN = (
+ r"(?:"
+ r"[0-9a-fA-F]{32}|"
+ r"[0-9a-fA-F]{64}|"
+ r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-"
+ r"[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"
+ r")"
+)
+_BRACKETED_DOCUMENT_RE = re.compile(
+ rf"^\[(?P<doc_id>{_DOCUMENT_ID_PATTERN})\]$"
)
# Match ``[N]`` — a 1-based citation marker with no surrounding chars.
@@ -49,19 +63,68 @@ _LIBRARY_PATH_RE = re.compile(
_CITATION_REF_RE = re.compile(r"^\[(\d+)\]$")
+@dataclass(frozen=True)
+class _LibraryReference:
+ value: str
+ suffix: Optional[str] = None
+
+
+def _decode_segment(value: str) -> str | None:
+ decoded = unquote(value)
+ if (
+ not decoded
+ or any(char in decoded for char in ("/", "\\", "?", "#"))
+ or any(ord(char) < 32 or ord(char) == 127 for char in decoded)
+ ):
+ return None
+ return decoded
+
+
+def _parse_library_reference(url: str) -> _LibraryReference | None:
+ if not isinstance(url, str):
+ return None
+
+ candidate = url.strip()
+ if not candidate:
+ return None
+
+ if "://" in candidate:
+ parsed = urlsplit(candidate)
+ if (
+ parsed.scheme != "https"
+ or parsed.netloc != "library.document"
+ or parsed.query
+ or parsed.fragment
+ ):
+ return None
+ candidate = f"/library/document{parsed.path}"
+
+ path_match = _LIBRARY_PATH_RE.match(candidate)
+ if path_match:
+ doc_id = _decode_segment(path_match.group("doc_id"))
+ if doc_id is None:
+ return None
+ return _LibraryReference(doc_id, path_match.group("suffix"))
+
+ bracket_match = _BRACKETED_DOCUMENT_RE.match(candidate)
+ if bracket_match:
+ return _LibraryReference(bracket_match.group("doc_id"))
+
+ return None
+
+
def parse_library_url(url: str) -> tuple[str, Optional[str]] | None:
- """Return ``(doc_id, suffix)`` for a ``/library/document/...`` URL, else ``None``.
+ """Return the local document reference and optional suffix, else ``None``.
``suffix`` is ``"pdf"`` for the PDF-direct form and ``None`` for the
- root document page. Both forms map to the same ``Document`` row; the
- suffix is captured so callers can decide how to render the result.
+ root document page. In addition to canonical library paths, this accepts
+ the ID-bound aliases emitted by the agent. Filename-only references remain
+ on the normal egress-denial path because filenames are guessable.
"""
- if not isinstance(url, str):
+ reference = _parse_library_reference(url)
+ if reference is None:
return None
- m = _LIBRARY_PATH_RE.match(url.strip())
- if not m:
- return None
- return m.group("doc_id"), m.group("suffix")
+ return reference.value, reference.suffix
def is_citation_reference(url: str) -> int | None:
@@ -97,10 +160,10 @@ def resolve_library_document(
``content=""``, which summary-mode handles as NOT RELEVANT without an
LLM call.)
"""
- parsed = parse_library_url(url)
- if parsed is None:
+ reference = _parse_library_reference(url)
+ if reference is None:
return None
- doc_id, _suffix = parsed
+ lookup_value = reference.value
if not username:
# No user context → no library. Caller falls through to the
@@ -124,12 +187,20 @@ def resolve_library_document(
try:
with get_user_db_session(username) as session:
- document = session.query(Document).filter_by(id=doc_id).first()
+ query = session.query(Document)
+ document = query.filter_by(id=lookup_value).first()
+ if document is None:
+ document = query.filter_by(document_hash=lookup_value).first()
+ if document is None and re.fullmatch(
+ r"[0-9a-fA-F]{32}", lookup_value
+ ):
+ canonical_id = str(uuid.UUID(hex=lookup_value))
+ document = query.filter_by(id=canonical_id).first()
if document is None:
return None
text = document.text_content or ""
return {
- "title": document.title or f"Document {doc_id}",
+ "title": document.title or f"Document {lookup_value}",
"content": text,
"url": url,
# ``snippet`` is what the collector registers as the
@@ -145,8 +216,9 @@ def resolve_library_document(
# DB hiccup is non-fatal; the tool returns a clean "not found" via
# None and the caller can fall through.
logger.exception(
- "library_resolver: failed to load document (doc_id={!r}, username={!r})",
- doc_id,
+ "library_resolver: failed to load document "
+ "(reference={!r}, username={!r})",
+ lookup_value,
username,
)
return None
diff --git a/tests/advanced_search_system/tools/test_library_resolver.py b/tests/advanced_search_system/tools/test_library_resolver.py
index 39ff160d1d..1ead3d7e16 100644
--- a/tests/advanced_search_system/tools/test_library_resolver.py
+++ b/tests/advanced_search_system/tools/test_library_resolver.py
@@ -11,7 +11,7 @@ denials).
from __future__ import annotations
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock, call, patch
# ---------------------------------------------------------------------------
@@ -49,6 +49,29 @@ def test_parse_library_url_trailing_slash():
)
+def test_parse_library_url_accepts_observed_document_aliases():
+ from local_deep_research.advanced_search_system.tools.fetch.library_resolver import (
+ parse_library_url,
+ )
+
+ doc_id = "123e4567-e89b-12d3-a456-426614174000"
+ assert parse_library_url(f"/lib/document/{doc_id}") == (doc_id, None)
+ assert parse_library_url(f"https://library.document/{doc_id}") == (
+ doc_id,
+ None,
+ )
+ assert parse_library_url(f"[{doc_id}]") == (doc_id, None)
+
+
+def test_parse_library_url_rejects_guessable_filename_forms():
+ from local_deep_research.advanced_search_system.tools.fetch.library_resolver import (
+ parse_library_url,
+ )
+
+ assert parse_library_url("/legacy/document/report%202024.txt") is None
+ assert parse_library_url("report 2024.txt") is None
+
+
def test_parse_library_url_rejects_non_matching_shapes():
from local_deep_research.advanced_search_system.tools.fetch.library_resolver import (
parse_library_url,
@@ -61,6 +84,18 @@ def test_parse_library_url_rejects_non_matching_shapes():
"/library/abc", # not under document/
"/library/document/abc/txt", # txt suffix is not library-DB route
"library/document/abc", # missing leading slash
+ "https://library.document.evil.test/abc",
+ "https://[email protected]/abc",
+ "https://library.document/abc?download=1",
+ "https://library.document:443/abc",
+ "https://library.document./abc",
+ "http://library.document/abc",
+ "/library/document/abc%00def",
+ "/library/document/abc%1fdef",
+ "/library/document/abc%7fdef",
+ "[42]", # numeric markers remain collector citation references
+ "[not-a-document-id]",
+ "bare words without an extension",
"",
None,
42,
@@ -147,6 +182,79 @@ def test_resolve_library_document_returns_shape_for_full_text():
assert result["snippet"] == "full body"
+def test_resolve_library_document_falls_back_to_document_hash():
+ from local_deep_research.advanced_search_system.tools.fetch.library_resolver import (
+ resolve_library_document,
+ )
+
+ doc_hash = "d" * 64
+ document = _fake_document(text_content="hash body", title="Hash Doc")
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as session_cm:
+ session = MagicMock()
+ id_query = MagicMock()
+ id_query.first.return_value = None
+ hash_query = MagicMock()
+ hash_query.first.return_value = document
+ session.query.return_value.filter_by.side_effect = [
+ id_query,
+ hash_query,
+ ]
+ session_cm.return_value.__enter__.return_value = session
+
+ result = resolve_library_document(
+ f"https://library.document/{doc_hash}", username="alice"
+ )
+
+ assert result is not None
+ assert result["content"] == "hash body"
+ assert session.query.return_value.filter_by.call_args_list == [
+ call(id=doc_hash),
+ call(document_hash=doc_hash),
+ ]
+
+
+def test_resolve_library_document_normalizes_32_hex_uuid():
+ from local_deep_research.advanced_search_system.tools.fetch.library_resolver import (
+ resolve_library_document,
+ )
+
+ compact_id = "fc524319abee46deb8b9415425fd77ec"
+ canonical_id = "fc524319-abee-46de-b8b9-415425fd77ec"
+ document = _fake_document(text_content="uuid body", title="UUID Doc")
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as session_cm:
+ session = MagicMock()
+ missing_id = MagicMock()
+ missing_id.first.return_value = None
+ missing_hash = MagicMock()
+ missing_hash.first.return_value = None
+ canonical_query = MagicMock()
+ canonical_query.first.return_value = document
+ session.query.return_value.filter_by.side_effect = [
+ missing_id,
+ missing_hash,
+ canonical_query,
+ ]
+ session_cm.return_value.__enter__.return_value = session
+
+ result = resolve_library_document(
+ f"/library/document/{compact_id}", username="alice"
+ )
+
+ assert result is not None
+ assert result["content"] == "uuid body"
+ assert session.query.return_value.filter_by.call_args_list == [
+ call(id=compact_id),
+ call(document_hash=compact_id),
+ call(id=canonical_id),
+ ]
+
+
def test_resolve_library_document_handles_empty_text():
"""An empty ``text_content`` is still a successful resolve — the
fetch tool's existing NOT RELEVANT guard handles the empty case."""