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.

refactor(citations): replace url_classifier disk-loader with a normal import (#4992) (#5041)

LearningCircuit53dd84e96d32
diff --git a/changelog.d/+lazy-content-fetcher-imports.refactor.md b/changelog.d/+lazy-content-fetcher-imports.misc.md
similarity index 100%
rename from changelog.d/+lazy-content-fetcher-imports.refactor.md
rename to changelog.d/+lazy-content-fetcher-imports.misc.md
diff --git a/changelog.d/+source-tag-cache-lookup.misc.md b/changelog.d/+source-tag-cache-lookup.misc.md
index 2d54ed8544..af8b598774 100644
--- a/changelog.d/+source-tag-cache-lookup.misc.md
+++ b/changelog.d/+source-tag-cache-lookup.misc.md
@@ -1 +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.
+Source-tagged citation formatting no longer re-runs the URL-classifier label lookup for every citation occurrence — the pre-computed label cache is consulted lazily, so each source's label resolves once. (The disk-loading import this originally worked around was removed entirely in #4992.)
diff --git a/changelog.d/4992.misc.md b/changelog.d/4992.misc.md
new file mode 100644
index 0000000000..31a28484e8
--- /dev/null
+++ b/changelog.d/4992.misc.md
@@ -0,0 +1 @@
+Removed the `importlib.util` disk-load workaround for `url_classifier` in `citation_formatter.py` (introduced in #4880). Now that `content_fetcher` no longer eagerly imports its heavy dependency tree (#5023), the formatter uses a normal `from ..content_fetcher.url_classifier import URLClassifier, URLType`. Also fixed two nits in the #5023 test file: an off-by-one project-root path in the subprocess tests and `check=True` calls that hid the subprocess stderr from failure reports.
diff --git a/src/local_deep_research/text_optimization/citation_formatter.py b/src/local_deep_research/text_optimization/citation_formatter.py
index fce11bb6c1..e2af5237b9 100644
--- a/src/local_deep_research/text_optimization/citation_formatter.py
+++ b/src/local_deep_research/text_optimization/citation_formatter.py
@@ -2,74 +2,12 @@
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
+from ..content_fetcher.url_classifier import URLClassifier, URLType
_SOURCES_SECTION_PATTERNS = [
@@ -624,11 +562,8 @@ class CitationFormatter:
over URL-derived tags when present for a given citation.
"""
- # Pre-compute tags so comma-separated [1, 2, 3] and standalone
- # [N] refs resolve to the same string for a given citation.
- # Without this, _extract_source_label's lazy URLClassifier import
- # can succeed on the 2nd+ call but fail on the 1st, producing
- # inconsistent labels (e.g. "arxiv.org-1" vs "arxiv-1").
+ # Pre-compute tags so each URL-having source resolves its label
+ # once, however many [N] / [1, 2, 3] refs cite it.
tag_cache: Dict[str, str] = {
num: self._extract_source_label(
url, collection=collections.get(num)
@@ -776,14 +711,6 @@ class CitationFormatter:
if scheme not in ("http", "https"):
return "local"
- # 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
# is a known academic source whose enum value is the short tag.
diff --git a/tests/content_fetcher/test_lazy_content_fetcher.py b/tests/content_fetcher/test_lazy_content_fetcher.py
index abe10eb22e..8e6219991f 100644
--- a/tests/content_fetcher/test_lazy_content_fetcher.py
+++ b/tests/content_fetcher/test_lazy_content_fetcher.py
@@ -42,7 +42,7 @@ _HEAVY_FRAGMENTS = (
def _measure_heavy_imports(import_stmt: str) -> list[str]:
"""Run ``import_stmt`` in a fresh interpreter and return the heavy
modules pulled into ``sys.modules`` as a side effect."""
- project_root = Path(__file__).resolve().parents[3]
+ project_root = Path(__file__).resolve().parents[2]
script = textwrap.dedent(
f"""
import sys
@@ -63,7 +63,11 @@ def _measure_heavy_imports(import_stmt: str) -> list[str]:
capture_output=True,
text=True,
cwd=str(project_root),
- check=True,
+ check=False,
+ )
+ assert result.returncode == 0, (
+ f"import subprocess failed: stdout={result.stdout!r} "
+ f"stderr={result.stderr!r}"
)
return [line for line in result.stdout.splitlines() if line]
@@ -137,7 +141,7 @@ class TestContentFetcherIsLazy:
[sys.executable, "-c", script],
capture_output=True,
text=True,
- cwd=str(Path(__file__).resolve().parents[3]),
+ cwd=str(Path(__file__).resolve().parents[2]),
check=False,
)
assert result.returncode == 0, (
@@ -213,8 +217,11 @@ class TestHeavyDepsOnlyLoadWithContentFetcher:
[sys.executable, "-c", script],
capture_output=True,
text=True,
- cwd=str(Path(__file__).resolve().parents[3]),
- check=True,
+ cwd=str(Path(__file__).resolve().parents[2]),
+ check=False,
+ )
+ assert result.returncode == 0, (
+ f"subprocess failed: stdout={result.stdout!r} stderr={result.stderr!r}"
)
assert result.stdout.strip() == "False", (
f"expected 'False', got {result.stdout.strip()!r}"
@@ -237,8 +244,11 @@ class TestHeavyDepsOnlyLoadWithContentFetcher:
[sys.executable, "-c", script],
capture_output=True,
text=True,
- cwd=str(Path(__file__).resolve().parents[3]),
- check=True,
+ cwd=str(Path(__file__).resolve().parents[2]),
+ check=False,
+ )
+ assert result.returncode == 0, (
+ f"subprocess failed: stdout={result.stdout!r} stderr={result.stderr!r}"
)
before, after = result.stdout.strip().split()
assert before == "False", (
diff --git a/tests/text_optimization/test_citation_formatter.py b/tests/text_optimization/test_citation_formatter.py
index 1f638e0c29..4bd3e70fa0 100644
--- a/tests/text_optimization/test_citation_formatter.py
+++ b/tests/text_optimization/test_citation_formatter.py
@@ -2400,8 +2400,8 @@ class TestSlugifyTitle:
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."""
+ cache hits — 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
@@ -2431,9 +2431,9 @@ class TestSourceTagCacheLookup:
assert "[[example.com-2]](https://example.com/x)" in result
assert len(calls) == len(sources)
- def test_url_less_source_uses_lazy_fallback(self):
+ def test_url_less_source_uses_cache_miss_fallback(self):
"""Sources without a URL are absent from tag_cache and must
- still resolve via the lazy fallback path."""
+ still resolve via the cache-miss fallback path."""
formatter = CitationFormatter(CitationMode.SOURCE_TAGGED_HYPERLINKS)
result = formatter._format_source_tagged_hyperlinks(
"see [1]", {"1": ("Title", "")}, {}
@@ -2442,96 +2442,23 @@ class TestSourceTagCacheLookup:
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."""
+class TestUrlClassifierIsNormalImport:
+ """#4992 follow-up: the disk-load workaround (PR #4880) is gone.
- def test_module_loaded_once_per_process(self, monkeypatch):
- import importlib.util
+ ``citation_formatter`` now imports ``URLClassifier``/``URLType``
+ through the package like any other module; the classes it uses must
+ be the canonical ones, not a shadow copy exec'd from disk (the old
+ loader produced a distinct module object whose enum members compared
+ unequal to the real ones)."""
- from local_deep_research.text_optimization import (
- citation_formatter as cf,
+ def test_uses_canonical_url_classifier_classes(self):
+ from local_deep_research.content_fetcher.url_classifier import (
+ URLClassifier,
+ URLType,
)
-
- 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"
- )
+ assert cf.URLClassifier is URLClassifier
+ assert cf.URLType is URLType