~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(web): defer WeasyPrint import so it no longer blocks server cold start (#4431) (#4734)
LearningCircuit189d4f0cae25
diff --git a/changelog.d/4734.bugfix.md b/changelog.d/4734.bugfix.mdnew file mode 100644index 0000000000..8704f0718a--- /dev/null+++ b/changelog.d/4734.bugfix.md@@ -0,0 +1 @@+WeasyPrint (the PDF-export dependency) is now imported lazily on first use instead of at web-server startup. It was previously imported during blueprint registration via `research_routes`, adding ~20s of "cold heavy-import" to server cold start on CPU-constrained CI runners — a contributor to the `Navigation timeout 60000ms` UI-shard flakiness in #4431. PDF export behaviour is unchanged.diff --git a/src/local_deep_research/web/services/pdf_service.py b/src/local_deep_research/web/services/pdf_service.pyindex b263726803..c73bcbfaec 100644--- a/src/local_deep_research/web/services/pdf_service.py+++ b/src/local_deep_research/web/services/pdf_service.py@@ -16,21 +16,57 @@ from typing import Optional, Dict, Anyimport markdown # type: ignore[import-untyped]from loguru import logger-try:- from weasyprint import HTML, CSS- from weasyprint.urls import URLFetcher-- WEASYPRINT_AVAILABLE = True-except (OSError, ImportError) as _weasyprint_err:- HTML = None # type: ignore[assignment,misc]- CSS = None # type: ignore[assignment,misc]- URLFetcher = None # type: ignore[assignment,misc]- WEASYPRINT_AVAILABLE = False- logger.warning("WeasyPrint not available — PDF export will be disabled")-from ...security import validate_url+# WeasyPrint pulls in Pango/Cairo/fontTools — a heavy, multi-second import.+# This module is imported eagerly during blueprint registration+# (research_routes -> pdf_service), so importing WeasyPrint at module load+# blocked web-server cold start by ~20s on CPU-constrained CI runners+# (issue #4431: "cold heavy-import under CI 2-core starvation"). PDF export is+# a rare, on-demand operation, so the import is deferred to first use.+#+# These names stay module-level (filled in by _ensure_weasyprint) so the+# render path — and the tests that patch them — keep working as before; they+# are just populated lazily instead of at import time.+HTML = None # type: ignore[assignment,misc]+CSS = None # type: ignore[assignment,misc]+# None until the import is attempted; True/False once determined.+WEASYPRINT_AVAILABLE: Optional[bool] = None+++def _ensure_weasyprint() -> None:+ """Import WeasyPrint on first use, populating the module-level globals.++ Idempotent: the import is attempted once and the outcome cached in+ ``WEASYPRINT_AVAILABLE``. Handles the same ``(OSError, ImportError)``+ failure modes (e.g. missing Pango/Cairo system libraries) the original+ module-level guard did.+ """+ global HTML, CSS, WEASYPRINT_AVAILABLE, _URL_FETCHER+ if WEASYPRINT_AVAILABLE is not None:+ return+ try:+ from weasyprint import HTML as _HTML, CSS as _CSS+ from weasyprint.urls import URLFetcher++ HTML, CSS = _HTML, _CSS+ _URL_FETCHER = URLFetcher(allow_redirects=False)+ WEASYPRINT_AVAILABLE = True+ except (OSError, ImportError):+ WEASYPRINT_AVAILABLE = False+ logger.warning("WeasyPrint not available — PDF export will be disabled")+++def weasyprint_available() -> bool:+ """Return True when WeasyPrint and its system libraries can be imported.++ Triggers the lazy import on first call.+ """+ _ensure_weasyprint()+ return bool(WEASYPRINT_AVAILABLE)++_WEASYPRINT_DOCS_URL = ("https://doc.courtbouillon.org/weasyprint/stable/first_steps.html")@@ -40,14 +76,12 @@ class UnsafePDFResourceURLError(ValueError):"""Subclasses ValueError so WeasyPrint skips the resource instead of aborting the render."""-# Module-level URLFetcher preserves the allow_redirects=False posture that-# default_url_fetcher hard-coded. Redirects disabled keeps the SSRF guard-# airtight — validate_url only inspects the initial URL, so a 30x to a-# cloud metadata endpoint (see ssrf_validator.ALWAYS_BLOCKED_METADATA_IPS)-# would otherwise slip past.-_URL_FETCHER = (- URLFetcher(allow_redirects=False) if WEASYPRINT_AVAILABLE else None-)+# Populated by _ensure_weasyprint() on first PDF use. The URLFetcher preserves+# the allow_redirects=False posture that default_url_fetcher hard-coded.+# Redirects disabled keeps the SSRF guard airtight — validate_url only inspects+# the initial URL, so a 30x to a cloud metadata endpoint (see+# ssrf_validator.ALWAYS_BLOCKED_METADATA_IPS) would otherwise slip past.+_URL_FETCHER = Nonedef _safe_url_fetcher(url):@@ -57,6 +91,7 @@ def _safe_url_fetcher(url):raise UnsafePDFResourceURLError(f"Blocked unsafe URL in PDF rendering: {url}")+ _ensure_weasyprint()return _URL_FETCHER.fetch(url)@@ -190,6 +225,9 @@ class PDFService:def __init__(self):"""Initialize PDF service with minimal CSS for readability."""+ # Defer-load WeasyPrint (lazy import) before using CSS, then+ # build the stylesheet from the module-level MINIMAL_CSS constant.+ _ensure_weasyprint()self.minimal_css = CSS(string=MINIMAL_CSS)def markdown_to_pdf(@@ -221,6 +259,7 @@ class PDFService:- Timeouts (30-60 seconds)- Worker recycling after 100 requests"""+ _ensure_weasyprint()try:# Convert markdown to HTMLhtml_content = self._markdown_to_html(@@ -327,6 +366,7 @@ def get_pdf_service() -> PDFService:MissingPDFDependencyError: If WeasyPrint system libraries are notavailable, with platform-specific installation instructions."""+ _ensure_weasyprint()if not WEASYPRINT_AVAILABLE:raise MissingPDFDependencyError(get_weasyprint_install_instructions())global _pdf_servicediff --git a/tests/exporters/test_pdf_exporter.py b/tests/exporters/test_pdf_exporter.pyindex 4be8f000e2..f6e951e7ad 100644--- a/tests/exporters/test_pdf_exporter.py+++ b/tests/exporters/test_pdf_exporter.py@@ -3,11 +3,11 @@import pytestfrom unittest.mock import patch, MagicMock-from local_deep_research.web.services.pdf_service import WEASYPRINT_AVAILABLE+from local_deep_research.web.services.pdf_service import weasyprint_available# Skip all tests that need real PDF generation when WeasyPrint is unavailableneeds_weasyprint = pytest.mark.skipif(- not WEASYPRINT_AVAILABLE,+ not weasyprint_available(),reason="WeasyPrint system libraries not available",)diff --git a/tests/web/services/test_pdf_service.py b/tests/web/services/test_pdf_service.pyindex f2c76efded..10d18cfa99 100644--- a/tests/web/services/test_pdf_service.py+++ b/tests/web/services/test_pdf_service.py@@ -478,6 +478,7 @@ class TestSafeUrlFetcher:_safe_url_fetcher,)+ pdf_module._ensure_weasyprint() # populate the lazy _URL_FETCHERwith (patch.object(pdf_module, "validate_url", return_value=True),patch.object(pdf_module._URL_FETCHER, "fetch") as mock_fetch,@@ -503,6 +504,7 @@ class TestSafeUrlFetcher:from local_deep_research.web.services import pdf_service as pdf_modulefrom urllib.request import HTTPRedirectHandler+ pdf_module._ensure_weasyprint() # populate the lazy _URL_FETCHERredirect_handlers = [hfor h in pdf_module._URL_FETCHER.handlers