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.

perf(citations): resolve source-tag labels from cache lazily (#5007)

LearningCircuit68c21c206b27
diff --git a/changelog.d/+source-tag-cache-lookup.misc.md b/changelog.d/+source-tag-cache-lookup.misc.md
new file mode 100644
index 0000000000..2d54ed8544
--- /dev/null
+++ b/changelog.d/+source-tag-cache-lookup.misc.md
@@ -0,0 +1 @@
+Source-tagged citation formatting no longer re-runs the URL-classifier label lookup (a disk-loading import) for every citation occurrence: the pre-computed label cache is now consulted lazily, the disk-loaded `url_classifier` module is memoized per process, and load failures are logged instead of silently degrading to domain labels.
diff --git a/src/local_deep_research/text_optimization/citation_formatter.py b/src/local_deep_research/text_optimization/citation_formatter.py
index 234435cac4..fce11bb6c1 100644
--- a/src/local_deep_research/text_optimization/citation_formatter.py
+++ b/src/local_deep_research/text_optimization/citation_formatter.py
@@ -3,11 +3,75 @@
import re
from enum import Enum
from pathlib import Path
+from types import ModuleType
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse
+from loguru import logger
from slugify import slugify
+# Memoized module object for the disk-loaded url_classifier (see
+# _load_url_classifier). None = not loaded yet; load failures are NOT
+# memoized, so a transient failure can recover on a later call.
+_url_classifier_mod: Optional[ModuleType] = None
+
+
+def _load_url_classifier() -> Optional[ModuleType]:
+ """Load ``content_fetcher/url_classifier.py`` directly from disk.
+
+ We must avoid going through ``content_fetcher/__init__.py`` because
+ it eagerly imports ``ContentFetcher`` and its heavy transitive
+ dependency tree (requests, playwright, sqlalchemy, …). Loading the
+ file directly keeps the formatter usable when that stack isn't
+ installed (e.g. minimal test setups). Tracked as follow-up tech
+ debt — once ``content_fetcher`` lazy-imports its heavy deps (see
+ #4992), this loader can be replaced with a normal ``from
+ ..content_fetcher.url_classifier import URLClassifier, URLType``.
+
+ Returns the loaded module, memoized per process, or ``None`` when
+ loading fails (callers fall back to domain-based labels).
+ """
+ global _url_classifier_mod
+ if _url_classifier_mod is not None:
+ return _url_classifier_mod
+ try:
+ import importlib.util
+
+ path = (
+ Path(__file__).resolve().parent.parent
+ / "content_fetcher"
+ / "url_classifier.py"
+ )
+ spec = importlib.util.spec_from_file_location("_url_classifier", path)
+ if spec is None or spec.loader is None:
+ logger.warning(
+ "url_classifier.py not loadable from {}; source-tagged "
+ "citations fall back to domain labels",
+ path,
+ )
+ return None
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ # Callers access these attributes unguarded — treat a module
+ # that loads but lacks them as a load failure so a broken file
+ # degrades to domain labels instead of raising mid-format.
+ if not hasattr(mod, "URLClassifier") or not hasattr(mod, "URLType"):
+ logger.warning(
+ "url_classifier.py at {} lacks URLClassifier/URLType; "
+ "source-tagged citations fall back to domain labels",
+ path,
+ )
+ return None
+ except Exception:
+ logger.exception(
+ "Failed to load url_classifier.py; source-tagged citations "
+ "fall back to domain labels"
+ )
+ return None
+ _url_classifier_mod = mod
+ return mod
+
+
_SOURCES_SECTION_PATTERNS = [
re.compile(
r"^#{1,3}\s*(?:Sources|References|Bibliography|Citations)",
@@ -575,12 +639,14 @@ class CitationFormatter:
def format_link(citation_num, data):
_, url = data
- label = tag_cache.get(
- citation_num,
- self._extract_source_label(
+ label = tag_cache.get(citation_num)
+ if label is None:
+ # Only URL-less sources are absent from tag_cache. Don't
+ # pass this as dict.get()'s default — that would evaluate
+ # the expensive lookup eagerly on every cache hit too.
+ label = self._extract_source_label(
url, collection=collections.get(citation_num)
- ),
- )
+ )
tag = f"{label}-{citation_num}"
# Only emit a hyperlink for http(s) URLs — local/file URLs are
# rendered as plain bracketed tags so the markdown stays clean
@@ -710,41 +776,13 @@ class CitationFormatter:
if scheme not in ("http", "https"):
return "local"
- # Lazy import to keep the formatter usable when the content_fetcher
- # package isn't importable (e.g. minimal test setups).
- #
- # We must avoid going through ``content_fetcher/__init__.py``
- # because it eagerly imports ``ContentFetcher`` and its heavy
- # transitive dependency tree (requests, playwright, sqlalchemy, …).
- # Instead, load ``url_classifier.py`` directly from disk using
- # ``importlib.util`` so the package chain is never entered.
- # Tracked as follow-up tech debt — once ``content_fetcher`` is
- # refactored to lazy-import its heavy deps (see #4992), this
- # loader can be replaced with a normal ``from
- # ..content_fetcher.url_classifier import URLClassifier, URLType``.
- try:
- import importlib.util
-
- _uc_path = (
- Path(__file__).resolve().parent
- / ".."
- / "content_fetcher"
- / "url_classifier.py"
- )
- _uc_spec = importlib.util.spec_from_file_location(
- "_url_classifier",
- _uc_path,
- )
- if _uc_spec is not None and _uc_spec.loader is not None:
- _uc_mod = importlib.util.module_from_spec(_uc_spec)
- _uc_spec.loader.exec_module(_uc_mod)
- URLClassifier = _uc_mod.URLClassifier
- URLType = _uc_mod.URLType
- else:
- return self._extract_domain(url)
- except Exception:
- # Full import failed — fall back to domain-based label.
+ # Loaded from disk (memoized per process) instead of a normal
+ # import — see _load_url_classifier for why.
+ _uc_mod = _load_url_classifier()
+ if _uc_mod is None:
return self._extract_domain(url)
+ URLClassifier = _uc_mod.URLClassifier
+ URLType = _uc_mod.URLType
url_type = URLClassifier.classify(url)
# Generic HTML/PDF/INVALID → fall back to domain. Everything else
diff --git a/tests/text_optimization/test_citation_formatter.py b/tests/text_optimization/test_citation_formatter.py
index c5264d42b4..1f638e0c29 100644
--- a/tests/text_optimization/test_citation_formatter.py
+++ b/tests/text_optimization/test_citation_formatter.py
@@ -2395,3 +2395,143 @@ class TestSlugifyTitle:
that is a real label, not a sentinel for "no meaningful slug"."""
assert CitationFormatter._slugify_title("Doc") == "doc"
assert CitationFormatter._slugify_title("DOC") == "doc"
+
+
+class TestSourceTagCacheLookup:
+ """_format_source_tagged_hyperlinks must resolve labels from the
+ pre-computed tag_cache without re-running _extract_source_label on
+ cache hits — the fallback loads url_classifier.py from disk, so
+ evaluating it per citation match is pure dead-weight work."""
+
+ def test_label_resolution_runs_once_per_source(self, monkeypatch):
+ """_extract_source_label runs once per URL-having source (while
+ building tag_cache), not once per citation occurrence."""
+ formatter = CitationFormatter(CitationMode.SOURCE_TAGGED_HYPERLINKS)
+ calls = []
+ original = CitationFormatter._extract_source_label
+
+ def counting(self, url, collection=None):
+ calls.append(url)
+ return original(self, url, collection=collection)
+
+ monkeypatch.setattr(
+ CitationFormatter, "_extract_source_label", counting
+ )
+
+ content = "First [1], again [1], list [1, 2], and [2]."
+ sources = {
+ "1": ("Paper A", "https://arxiv.org/abs/2024.1111"),
+ "2": ("Paper B", "https://example.com/x"),
+ }
+ result = formatter._format_source_tagged_hyperlinks(
+ content, sources, {}
+ )
+
+ assert "[[arxiv-1]](https://arxiv.org/abs/2024.1111)" in result
+ assert "[[example.com-2]](https://example.com/x)" in result
+ assert len(calls) == len(sources)
+
+ def test_url_less_source_uses_lazy_fallback(self):
+ """Sources without a URL are absent from tag_cache and must
+ still resolve via the lazy fallback path."""
+ formatter = CitationFormatter(CitationMode.SOURCE_TAGGED_HYPERLINKS)
+ result = formatter._format_source_tagged_hyperlinks(
+ "see [1]", {"1": ("Title", "")}, {}
+ )
+ assert "[local-1]" in result
+ assert "[[local-1]]" not in result # no hyperlink for empty URL
+
+
+class TestLoadUrlClassifierMemo:
+ """The disk-loaded url_classifier module must be memoized so the
+ spec/exec machinery runs once per process, not once per label."""
+
+ def test_module_loaded_once_per_process(self, monkeypatch):
+ import importlib.util
+
+ from local_deep_research.text_optimization import (
+ citation_formatter as cf,
+ )
+
+ calls = []
+ original = importlib.util.spec_from_file_location
+
+ def counting(*args, **kwargs):
+ calls.append(args)
+ return original(*args, **kwargs)
+
+ monkeypatch.setattr(importlib.util, "spec_from_file_location", counting)
+ monkeypatch.setattr(cf, "_url_classifier_mod", None)
+
+ first = cf._load_url_classifier()
+ second = cf._load_url_classifier()
+
+ assert first is not None
+ assert first is second
+ assert len(calls) == 1
+
+ def test_load_failure_not_memoized_and_recovers(self, monkeypatch):
+ """A transient load failure returns None without poisoning the
+ memo, so the next call can succeed."""
+ import importlib.util
+
+ from local_deep_research.text_optimization import (
+ citation_formatter as cf,
+ )
+
+ calls = []
+ original = importlib.util.spec_from_file_location
+
+ def flaky(*args, **kwargs):
+ calls.append(args)
+ if len(calls) == 1:
+ raise OSError("disk hiccup")
+ return original(*args, **kwargs)
+
+ monkeypatch.setattr(importlib.util, "spec_from_file_location", flaky)
+ monkeypatch.setattr(cf, "_url_classifier_mod", None)
+
+ assert cf._load_url_classifier() is None
+ assert cf._url_classifier_mod is None # failure not memoized
+ recovered = cf._load_url_classifier()
+ assert recovered is not None
+ assert cf._url_classifier_mod is recovered
+
+ def test_module_missing_attributes_treated_as_load_failure(
+ self, monkeypatch, tmp_path
+ ):
+ """A module that execs fine but lacks URLClassifier/URLType must
+ return None (domain-label fallback), not surface AttributeError
+ from the unguarded attribute reads in _extract_source_label."""
+ import importlib.util
+
+ from local_deep_research.text_optimization import (
+ citation_formatter as cf,
+ )
+
+ empty = tmp_path / "empty_module.py"
+ empty.write_text("")
+ original = importlib.util.spec_from_file_location
+
+ def redirect(name, path, **kwargs):
+ return original(name, empty, **kwargs)
+
+ monkeypatch.setattr(importlib.util, "spec_from_file_location", redirect)
+ monkeypatch.setattr(cf, "_url_classifier_mod", None)
+
+ assert cf._load_url_classifier() is None
+ assert cf._url_classifier_mod is None
+
+ def test_loader_failure_falls_back_to_domain_label(self, monkeypatch):
+ """_extract_source_label degrades to the domain when the
+ classifier can't be loaded at all."""
+ from local_deep_research.text_optimization import (
+ citation_formatter as cf,
+ )
+
+ monkeypatch.setattr(cf, "_load_url_classifier", lambda: None)
+ formatter = CitationFormatter(CitationMode.SOURCE_TAGGED_HYPERLINKS)
+ assert (
+ formatter._extract_source_label("https://example.com/x")
+ == "example.com"
+ )