~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(security): bound uploaded document parser processes (#7147)
LearningCircuitd54e8957b305
diff --git a/.github/workflows/docker-tests.yml b/.github/workflows/docker-tests.ymlindex a7ce2136d3..91ad888019 100644--- a/.github/workflows/docker-tests.yml+++ b/.github/workflows/docker-tests.yml@@ -108,6 +108,7 @@ jobs:- 'requirements/bootstrap-*.txt'- 'requirements/pip-vendor-refresh.txt'- 'scripts/refresh_pip_urllib3.py'+ - 'scripts/install_nltk_data.py'- 'tests/ci/standalone/verify_pip_vendor.py'- 'scripts/ldr_entrypoint.sh'- 'scripts/ollama_entrypoint.sh'@@ -120,6 +121,7 @@ jobs:# verify encrypted data access across a clean stop/restart.- 'src/local_deep_research/**'- 'tests/ci/standalone/production_lifecycle.py'+ - 'tests/ci/standalone/verify_upload_parser.py'- '.github/workflows/docker-tests.yml'accessibility:# Theme palettes (and the loader/schema that validate them) are@@ -1617,6 +1619,15 @@ jobs:EXPECTED_ARCH: ${{ matrix.arch }}run: test "$(docker image inspect ldr-prod --format '{{.Architecture}}')" = "$EXPECTED_ARCH"+ - name: Verify upload parser and NLTK data offline as service user+ run: |+ timeout 120s docker run --rm --network none --user ldruser \+ --read-only --tmpfs /tmp:rw,noexec,nosuid,size=64m \+ -e AUTO_DOWNLOAD_NLTK=false -e SCARF_NO_ANALYTICS=true \+ -v "$PWD/tests/ci/standalone/verify_upload_parser.py:/tmp/verify_upload_parser.py:ro" \+ --entrypoint /install/.venv/bin/python \+ ldr-prod /tmp/verify_upload_parser.py+- name: Verify file ownership and playwright accessrun: |docker run --rm ldr-prod sh -c 'diff --git a/.grype.yaml b/.grype.yamlindex 7695e769b3..5e5fb03074 100644--- a/.grype.yaml+++ b/.grype.yaml@@ -490,16 +490,25 @@ ignore:- vulnerability: CVE-2026-22693reason: "NULL deref on malloc failure in SubtableUnicodesCache. Debian trixie no-dsa. Sid 12.3.2."- # --- nltk (transitive dep, never imported — no fix available, 3.9.3 is latest) ---+ # --- nltk (transitive dep of unstructured) ---+ # All three advisories cover nltk <= 3.9.3 and are fixed in 3.9.4; pdm.lock+ # pins nltk 3.10.3, so none of them matches the image and these entries+ # can be deleted. Kept, with corrected reasons, until a scan confirms it.+ # nltk IS imported: unstructured's text classification (Word, PowerPoint,+ # .xlsx, HTML uploads) tokenizes and tags with it. The image ships the+ # NLTK data it needs (Dockerfile nltk-data stage, fetched with pinned+ # SHA-256 by scripts/install_nltk_data.py, not nltk.download()), so+ # unstructured's import-time nltk.download() finds the data present and+ # does not run; the upload parser child sets AUTO_DOWNLOAD_NLTK=false.- vulnerability: GHSA-jm6w-m3j8-898gpackage: { name: nltk }- reason: "High vuln in nltk 3.9.3 (Zip Slip in downloader). Transitive dep; project never calls nltk.download(). No fix released."+ reason: "High vuln in nltk <= 3.9.3 (unauthenticated remote shutdown in nltk.app.wordnet_app). Fixed in 3.9.4; locked nltk is 3.10.3. LDR never starts the WordNet browser app."- vulnerability: GHSA-rf74-v2fm-23pwpackage: { name: nltk }- reason: "Medium vuln in nltk 3.9.3. Transitive dep; nltk never imported or used directly. No fix released."+ reason: "Medium vuln in nltk <= 3.9.3 (unbounded recursion in JSONTaggedDecoder.decode_obj). Fixed in 3.9.4; locked nltk is 3.10.3. The tagger data LDR loads is read with json.load, not JSONTaggedDecoder."- vulnerability: GHSA-gfwx-w7gr-fvh7package: { name: nltk }- reason: "Medium vuln in nltk 3.9.3. Transitive dep; nltk never imported or used directly. No fix released."+ reason: "Medium vuln in nltk <= 3.9.3 (XSS in web page generation). Fixed in 3.9.4; locked nltk is 3.10.3. LDR serves no nltk-generated HTML."# ==========================================================================# UNSTRUCTURED (GHSA-4mvj-m6j5-pmf7 / CVE-2026-71428 — alerts #8196, #8197)diff --git a/Dockerfile b/Dockerfileindex 3920b17aa9..bd14f3f71c 100644--- a/Dockerfile+++ b/Dockerfile@@ -322,6 +322,22 @@ RUN groupadd -r ldruser && useradd -r -g ldruser -u 1000 -m -d /home/ldruser ldr# permission tests above) opt into `--user ldruser` individually instead# of flipping the whole stage non-root.+####+# Fetches the NLTK data the upload parser needs.+####+FROM builder-base AS nltk-data++# The bounded upload parser child (security/isolated_loader.py) sets+# AUTO_DOWNLOAD_NLTK=false, so unstructured's Word, PowerPoint, .xlsx and+# HTML text classification finds this data in the image or the upload fails.+# The script fetches each archive from one pinned nltk_data commit and+# checks its size and SHA-256 before extracting it; NLTK's own downloader+# would take whatever the mutable gh-pages index lists, unchecked. Keep its+# package list equal to isolated_loader.NLTK_DATA_PACKAGES.+COPY scripts/install_nltk_data.py /tmp/install_nltk_data.py+RUN python3 -I /tmp/install_nltk_data.py /nltk_data \+ && rm /tmp/install_nltk_data.py+##### Runs the LDR service.###@@ -404,6 +420,12 @@ RUN mkdir -p /app/.config/local_deep_research /home/ldruser/.local/share && \COPY --chown=ldruser:ldruser --from=builder /install/.venv/ /install/.venvENV PATH="/install/.venv/bin:$PATH"+# NLTK data for the upload parser (see the nltk-data stage). The directory+# is on NLTK's default search path (nltk.data.path) for every user on+# Linux, so the server and its parser children find it as ldruser without+# NLTK_DATA. It stays root-owned: ldruser can read it but not replace it.+COPY --from=nltk-data /nltk_data/ /usr/local/share/nltk_data/+# Strip world-write bit from the migrations subtree. The runtime check in# alembic_runner._validate_migrations_permissions refuses to run migrations# if anything under migrations/versions/ is world-writable, and pip/pdm candiff --git a/changelog.d/+unstructured-telemetry-opt-out.security.md b/changelog.d/+unstructured-telemetry-opt-out.security.mdnew file mode 100644index 0000000000..7b9a857405--- /dev/null+++ b/changelog.d/+unstructured-telemetry-opt-out.security.md@@ -0,0 +1 @@+Importing LDR sets `SCARF_NO_ANALYTICS=true` in its process environment, overriding any existing value. Parser children receive the same setting, disabling unstructured's import-time usage request. `DO_NOT_TRACK` remains unchanged.diff --git a/changelog.d/7147.security.md b/changelog.d/7147.security.mdnew file mode 100644index 0000000000..568e5991fc--- /dev/null+++ b/changelog.d/7147.security.md@@ -0,0 +1,5 @@+Run the final uploaded Office, spreadsheet, HTML, MHTML, Markdown, email, XML and Evernote parsers in child processes after the existing archive checks and bounded conversions. Each parse has a 90-second deadline, a 10-million-character text limit, a 10,000-document limit and a 40 MB result limit, including metadata. Linux adds a soft 3 GiB data-memory limit; allocation failures reported by the parser refuse the parse, while libraries may handle failed allocations internally. This is not a whole-process memory ceiling. Children also have a 120-second CPU-time limit on POSIX and request a parent-death signal on Linux.++At most two parsers run per server process, with capacity held through result validation. Busy uploads report that the file can be uploaded again. Results travel over a bounded in-memory pipe, with collection limits checked before JSON decoding.++The Docker image ships the required NLTK data from pinned, hash-checked archives, and CI checks a normal Office parse offline as the service user on both image architectures. Other installations must install `punkt_tab` and `averaged_perceptron_tagger_eng` once. Source-tree runs must install LDR or expose its absolute `src` directory through `PYTHONPATH`. Each file starts a fresh interpreter, so multi-file uploads may need a longer reverse-proxy read timeout. See the library guide for format and platform scope.diff --git a/docs/library-and-rag.md b/docs/library-and-rag.mdindex 38b5e86194..969f200da9 100644--- a/docs/library-and-rag.md+++ b/docs/library-and-rag.md@@ -94,6 +94,83 @@ with size and complexity limits; for a package with UTF-16 XML parts, resavethe document in Office or LibreOffice to produce UTF-8 parts. The releasenotes list every limit.+The final Office/spreadsheet, HTML, MHTML (`.mht`/`.mhtml`), Markdown,+email, XML and Evernote parser runs in a separate child process with a 90-second deadline, a 10-million-character+text limit and a 10,000-document limit, and its result is capped at 40 MB+including metadata. This includes files converted from legacy Office,+OpenDocument, EPUB and pandoc-backed formats. On Linux, each parser child+also has a soft 3 GiB data-memory limit, of which the parser libraries+themselves use several hundred MB. It is soft in two ways: it is the soft+`RLIMIT_DATA` limit, which code in the child could raise again up to the hard+limit, and it counts the data segment and private writable mappings, not the+child's whole memory use. Allocation failures reported by the parser refuse+the parse; a library may handle a failed allocation internally. This limit+does not guarantee a whole-process memory ceiling and is unavailable on other operating+systems. If the server process crashes or is killed during a parse, nothing+enforces the deadline any more, so the child also stops itself: on Linux and+macOS it is ended after 120 seconds of CPU time, and on Linux it is killed as+soon as the server process exits. Windows has neither safeguard. Every such+file starts a fresh child that imports the parser+libraries again, which adds about 2.5 to 5.5 seconds per file for a small+document on a development machine, and more on slower hosts. The upload page+sends at most 15 files per request and the server parses them one after+another, so a request of 15 such files spends about 40 to 80 seconds in+parser children on that machine before it can finish. Behind a reverse+proxy, allow for this in its read timeout: nginx's default+`proxy_read_timeout` is 60 seconds, and the+[reverse-proxy guide](deployment/reverse-proxy.md)'s example uses 300. At+most two of these parsers run at once per server process; an upload arriving+while both are busy reports "Document parser busy with other uploads; upload+this file again" for that file instead of an extraction failure, and the same+file can be uploaded again once the other uploads finish. Plain-text, CSV,+TSV, JSON, YAML, TOML and notebook uploads retain their existing parsing+path. PDFs retain their separate page, character and CPU-time limits.+Image/OCR support depends on optional packages and system tools and is+outside this child-parser change.++Markdown and email HTML bodies use the same child boundary. Email+attachments remain excluded from parsing. Evernote notes retain their+metadata, including dates, optional values and tags. A very large Evernote+export (roughly 9,000 notes or more in one `.enex` file) exceeds the+per-file metadata and document limits and is not imported; export the+notebooks as several smaller files instead.++The parser child never downloads NLTK data. Its Word, PowerPoint, `.xlsx`,+HTML, Markdown, email (`.eml`) and XML parsers (unstructured) classify text+with NLTK's `punkt_tab` and `averaged_perceptron_tagger_eng` data, and so do+the formats converted to them (`.doc`, `.ppt`, `.odt`, `.epub`, `.rtf`, `.rst`, `.org`).++- **Docker image:** the image ships this data in+ `/usr/local/share/nltk_data`, which is on NLTK's default search path for+ every user, the unprivileged `ldruser` the container runs as included.+ Nothing needs installing. The build fetches each archive from a pinned+ commit of `nltk/nltk_data` and checks its SHA-256+ (`scripts/install_nltk_data.py`).+- **pip and source installs:** the pip package does not include the data.+ Until it is installed, an upload that needs it reports "NLTK data needed+ to parse this file is not installed on the server" for that file, with+ the command `python -m nltk.downloader punkt_tab+ averaged_perceptron_tagger_eng`. Run that command once with the server's Python environment, as+ the user that runs the server: by default it installs the data into that+ user's `~/nltk_data` (`%APPDATA%\nltk_data` on Windows). To keep it+ elsewhere, add `-d <directory>` to the command and set+ `NLTK_DATA=<directory>` in the server's environment.++The child starts with Python's `-P` option and without empty `PYTHONPATH`+entries, which Python reads as the working directory. Set `PYTHONPATH`+explicitly when using a source tree; installed packages remain available.+++For source-tree runs, install LDR in the server's environment (for example,+with the repository's development setup) or set `PYTHONPATH` to the absolute+`src` directory. Starting the server from inside `src/` alone does not make+the package available to a child started with `-P`.++Importing LDR sets `SCARF_NO_ANALYTICS=true` in its process environment,+overwriting any existing value; parser children receive the same setting.+This disables unstructured's import-time usage request. `DO_NOT_TRACK` is+left unchanged.+`.rtf`, `.epub`, `.rst`, `.org` and `.odt` uploads are converted with pandocrun with `--sandbox`, which needs pandoc 2.15 or newer: the bundled`pypandoc-binary` ships a pandoc 3 build, but if an older pandoc is founddiff --git a/scripts/install_nltk_data.py b/scripts/install_nltk_data.pynew file mode 100644index 0000000000..ad86c6ee09--- /dev/null+++ b/scripts/install_nltk_data.py@@ -0,0 +1,182 @@+"""Install the NLTK data the upload parser needs into the Docker image.++The bounded upload parser child (security/isolated_loader.py) never+downloads NLTK data, so the image ships the packages that unstructured's+text classification loads (``unstructured/nlp/tokenize.py``): the+``punkt_tab`` sentence tokenizer and the ``averaged_perceptron_tagger_eng``+part-of-speech tagger.++NLTK's own downloader fetches whatever its index on the mutable+``gh-pages`` branch lists and checks nothing it could not also have been+served. This script instead fetches each archive from one pinned commit of+github.com/nltk/nltk_data, refuses it unless its size and SHA-256 match the+values below (the same values as that commit's ``index.xml``), and extracts+only regular files under the package's own directory.++Usage: python3 -I install_nltk_data.py <destination directory>++To update, pick a newer nltk_data commit and copy each package's ``size``+and ``sha256_checksum`` from ``index.xml`` at that commit.+"""++from __future__ import annotations++import hashlib+import io+import os+import stat+import sys+import time+import urllib.request+import zipfile+from pathlib import Path, PurePosixPath+from typing import Callable, NamedTuple++NLTK_DATA_COMMIT = "550b6625bcef1f2abff2ff770a5a0d272c9c6b2a"+URL_TEMPLATE = (+ "https://raw.githubusercontent.com/nltk/nltk_data/"+ "{commit}/packages/{subdir}/{name}.zip"+)+# Extracted bytes per package; both are about 11 MB or less.+MAX_UNZIPPED_BYTES = 64 * 1024 * 1024+++class Package(NamedTuple):+ subdir: str+ name: str+ size: int+ sha256: str+++# Keep the names equal to isolated_loader.NLTK_DATA_PACKAGES.+PACKAGES = (+ Package(+ "tokenizers",+ "punkt_tab",+ 4_319_076,+ "e57f64187974277726a3417ca6f181ec5403676c717672eef6a748a7b20e0106",+ ),+ Package(+ "taggers",+ "averaged_perceptron_tagger_eng",+ 1_539_115,+ "6025f530624335c67d6547d44757b357b4e79bae030a0383e9887a92c1718f0b",+ ),+)+++def package_url(package: Package) -> str:+ return URL_TEMPLATE.format(+ commit=NLTK_DATA_COMMIT, subdir=package.subdir, name=package.name+ )+++def fetch(url: str, limit: int) -> bytes:+ """Return at most *limit* + 1 bytes of *url*, retrying transient errors."""+ if not url.startswith("https://"):+ raise ValueError(f"refusing non-HTTPS URL {url}")+ for attempt in range(1, 4):+ try:+ with urllib.request.urlopen(url, timeout=60) as response: # noqa: S310 https only, checked above+ return response.read(limit + 1)+ except OSError as exc:+ if attempt == 3:+ raise+ print(f"download of {url} failed ({exc}); retrying", flush=True)+ time.sleep(5 * attempt)+ raise AssertionError("unreachable")+++def verify(package: Package, archive: bytes) -> None:+ if len(archive) != package.size:+ raise ValueError(+ f"{package.name}: expected {package.size} bytes, got {len(archive)}"+ )+ digest = hashlib.sha256(archive).hexdigest()+ if digest != package.sha256:+ raise ValueError(+ f"{package.name}: SHA-256 mismatch: expected {package.sha256}, "+ f"got {digest}"+ )+++def _make_readable(path: Path, *, directory: bool) -> None:+ # World-readable by design: the image's unprivileged service account+ # must read this data. Nothing but the owner (root) can write it.+ os.chmod(path, 0o755 if directory else 0o644) # noqa: S103 read-only data for every user+++def extract(package: Package, archive: bytes, destination: Path) -> None:+ """Extract *archive* into ``destination/<subdir>/<name>/``.++ Every member must be a regular file or directory whose path stays under+ ``<name>/``; anything else refuses the whole archive before any file is+ written.+ """+ target = destination / package.subdir+ with zipfile.ZipFile(io.BytesIO(archive)) as bundle:+ members = bundle.infolist()+ total = 0+ for member in members:+ path = PurePosixPath(member.filename)+ # Unix file type bits, when the archive records them; a member+ # without them is a plain file or directory.+ file_type = stat.S_IFMT(member.external_attr >> 16)+ if (+ "\\" in member.filename+ or path.is_absolute()+ or ".." in path.parts+ or not path.parts+ or path.parts[0] != package.name+ or file_type not in (0, stat.S_IFREG, stat.S_IFDIR)+ ):+ raise ValueError(+ f"{package.name}: unsafe archive member {member.filename!r}"+ )+ total += member.file_size+ if total > MAX_UNZIPPED_BYTES:+ raise ValueError(f"{package.name}: archive expands too far")+ for member in members:+ out = target.joinpath(*PurePosixPath(member.filename).parts)+ if member.is_dir():+ out.mkdir(parents=True, exist_ok=True)+ continue+ out.parent.mkdir(parents=True, exist_ok=True)+ with bundle.open(member) as source, open(out, "wb") as sink:+ sink.write(source.read())+ # Readable by every user, writable by none but the owner (root), so the+ # unprivileged service account can load the data but not replace it.+ for root, dirs, files in (target / package.name).walk():+ _make_readable(root, directory=True)+ for name in dirs:+ _make_readable(root / name, directory=True)+ for name in files:+ _make_readable(root / name, directory=False)+++def install(+ destination: Path,+ fetcher: Callable[[str, int], bytes] = fetch,+) -> None:+ for package in PACKAGES:+ archive = fetcher(package_url(package), package.size)+ verify(package, archive)+ extract(package, archive, destination)+ print(f"installed NLTK {package.subdir}/{package.name}", flush=True)+ _make_readable(destination, directory=True)+ for package in PACKAGES:+ _make_readable(destination / package.subdir, directory=True)+++def main(argv: list[str]) -> int:+ if len(argv) != 2:+ print(__doc__, file=sys.stderr)+ return 2+ destination = Path(argv[1])+ destination.mkdir(parents=True, exist_ok=True)+ install(destination)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv))diff --git a/src/local_deep_research/__init__.py b/src/local_deep_research/__init__.pyindex 6347602168..fad4386bb4 100644--- a/src/local_deep_research/__init__.py+++ b/src/local_deep_research/__init__.py@@ -8,10 +8,15 @@ __description__ = "A tool for conducting deep research using AI"from loguru import loggerfrom .__version__ import __version__+from .config.unstructured_telemetry import opt_out_of_unstructured_telemetry# Disable logging by default to not interfere with user setup.logger.disable("local_deep_research")+# Before any module imports unstructured, whose first import in a process+# otherwise sends a usage request to its vendor.+opt_out_of_unstructured_telemetry()+__all__ = ["__version__",]diff --git a/src/local_deep_research/config/unstructured_telemetry.py b/src/local_deep_research/config/unstructured_telemetry.pynew file mode 100644index 0000000000..535486999e--- /dev/null+++ b/src/local_deep_research/config/unstructured_telemetry.py@@ -0,0 +1,25 @@+"""Opt out of the usage request that unstructured sends when imported.++unstructured, the parser behind the Office, HTML, Markdown, email and XML+loaders, calls ``scarf_analytics()`` the first time a process imports+``unstructured.logger``. Unless ``SCARF_NO_ANALYTICS`` or ``DO_NOT_TRACK``+is exactly ``"true"``, that sends a GET request naming the unstructured+and Python versions, operating system, CPU architecture and GPU presence+to packages.unstructured.io. A process sends it once, at that first import,+which is its first unstructured-backed parse.+"""++import os+from collections.abc import MutableMapping++# unstructured compares the value with "true" exactly, so "1" or "yes" does+# not opt out; the value is overwritten rather than kept. DO_NOT_TRACK is+# left alone because other libraries read it too (huggingface_hub, for one).+UNSTRUCTURED_TELEMETRY_OPT_OUT = {"SCARF_NO_ANALYTICS": "true"}+++def opt_out_of_unstructured_telemetry(+ env: MutableMapping[str, str] | None = None,+) -> None:+ """Set the opt-out in *env*, or in this process's environment."""+ (os.environ if env is None else env).update(UNSTRUCTURED_TELEMETRY_OPT_OUT)diff --git a/src/local_deep_research/document_loaders/bytes_loader.py b/src/local_deep_research/document_loaders/bytes_loader.pyindex 959144948d..25acae56f5 100644--- a/src/local_deep_research/document_loaders/bytes_loader.py+++ b/src/local_deep_research/document_loaders/bytes_loader.py@@ -13,7 +13,14 @@ from langchain_core.documents import Documentfrom loguru import loggerfrom local_deep_research.security.filename_sanitizer import sanitize_filename-+from local_deep_research.security.isolated_loader import (+ ISOLATED_FINAL_EXTENSIONS,+ NLTK_DATA_INSTALL_COMMAND,+ IsolatedLoaderError,+ ParserBusyError,+ ParserDataMissingError,+ load_documents_isolated,+)from .openpyxl_hardening import disable_openpyxl_drawing_readsfrom .zip_container_guard import (DecompressionBombError,@@ -47,8 +54,9 @@ def load_from_bytes(Load documents from bytes content.PDFs are extracted directly from memory with shared page, character,- and CPU ceilings. Other formats are written to a temporary file, loaded- with the registered LangChain loader, then cleaned up.+ and CPU ceilings. Other formats use a temporary file, with Office,+ spreadsheet, HTML, Markdown, email, XML and Evernote parsing+ isolated in a bounded child process, then clean it up.Args:content: File content as bytes@@ -61,6 +69,10 @@ def load_from_bytes(Raises:ValueError: If the extension is not supported+ IsolatedLoaderError: If the bounded parser timed out, exceeded a+ limit or failed, (as ParserBusyError) had no free slot, or+ (as ParserDataMissingError) needed NLTK data that is not+ installed"""# Defense in depth: re-sanitize filename even though callers# should have sanitized already@@ -135,10 +147,16 @@ def load_from_bytes(with tempfile.NamedTemporaryFile(suffix=ext, delete=False, prefix="ldr_upload_") as tmp:- tmp.write(content)tmp_path = tmp.name- loader = loader_class(tmp_path, **loader_kwargs)- documents = loader.load()+ tmp.write(content)+ # Run the registered structured document parsers behind a+ # killable boundary. The guard and bounded converters above run+ # first; a raw .doc/.ppt or pandoc loader would bypass them.+ if ext in ISOLATED_FINAL_EXTENSIONS:+ documents = load_documents_isolated(tmp_path, ext)+ else:+ loader = loader_class(tmp_path, **loader_kwargs)+ documents = loader.load()# Add metadata to all documentsfor doc in documents:@@ -151,6 +169,18 @@ def load_from_bytes()return documents+ except ParserBusyError:+ logger.warning("Document parser busy: every parser slot is in use")+ raise+ except ParserDataMissingError:+ logger.warning(+ "Document parser needs NLTK data that is not installed; install "+ f"it with: {NLTK_DATA_INSTALL_COMMAND}"+ )+ raise+ except IsolatedLoaderError:+ logger.warning("Document parser exceeded a limit or failed")+ raiseexcept (ImportError, ModuleNotFoundError):# The extension is registered but the loader's runtime parser# dependency is missing. The registry normally prevents this@@ -193,14 +223,30 @@ def extract_text_from_bytes(Returns:Extracted text as string, or None if extraction failed++ Raises:+ ParserBusyError: Every bounded parser slot was in use. Unlike a+ failed extraction, which returns None, this says nothing about+ the file, so the caller can ask for the same file again.+ ParserDataMissingError: The bounded parser needed NLTK data that+ is not installed on this server. This too says nothing about+ the file; the caller can tell the operator to install it."""try:documents = load_from_bytes(content, extension, filename)if documents:+ # The bounded child parse and bounded_pdf already count this+ # join against their character limits; the other loaders,+ # which run in this process, have no character limit.return "\n\n".join(doc.page_content for doc in documents if doc.page_content)return None+ except (ParserBusyError, ParserDataMissingError):+ raise+ except IsolatedLoaderError:+ logger.warning("Refused document: parsing or text exceeded its limits")+ return Noneexcept DecompressionBombError:# Every refusal of the zip-container guard lands here, ordinary# documents over its size, structure or parsing-work limits asdiff --git a/src/local_deep_research/document_loaders/zip_container_guard.py b/src/local_deep_research/document_loaders/zip_container_guard.pyindex 690dcb1a91..35d95ed13e 100644--- a/src/local_deep_research/document_loaders/zip_container_guard.py+++ b/src/local_deep_research/document_loaders/zip_container_guard.py@@ -227,7 +227,7 @@ openpyxl cannot resolve, are refused as ``DecompressionBombError``What this bounds, and what it does not:-- **In-process Python parsers** (python-docx, python-pptx, openpyxl,+- **Python parsers** (python-docx, python-pptx, openpyxl,unstructured for ``.docx``/``.xlsx``/``.pptx``): each *read* of anentry now yields at most its (verified) declared size. It does notbound parser memory or parser time. For an XML parse tree alone the@@ -274,7 +274,7 @@ What this bounds, and what it does not:Only an entry of an OOXML container whose first bytes carry a knownbinary signature earns the media ceiling — never a name: part namesare attacker-chosen and packages dispatch parts by content type.- Each signature is anchored so that no XML parser the in-process+ Each signature is anchored so that no XML parser the Pythonloaders use (lxml/expat) accepts it as a document start. EPUB andODT entries never earn it: pandoc reads an EPUB chapter by itsdeclared media type, not its bytes. All but two@@ -331,8 +331,9 @@ of the declarations, and only the specific fan-outs listed above.runs once per element at ~25 ms when the whole text is not onelanguage), so an accepted document of a few thousand suchparagraphs runs for minutes; and one 3 MB paragraph took 43 s and- ~300 MB. Nothing here bounds that; only a wall-clock and memory- limit on the in-process parse would.+ ~300 MB. Nothing here bounds that; on the upload path the parser+ child's deadline does, and on Linux its memory limit (see the last+ item).- **.docx length refusals.** The ceilings share one budget and priceeach step at the slowest layout measured, so they also refuse longordinary documents that would partition in under a minute. Measured@@ -363,11 +364,17 @@ of the declarations, and only the specific fan-outs listed above.3 GB). ``document.xml`` and relationships parts are not affected: anelement over ``MAX_DOCX_ELEMENT_ATTRIBUTES`` or``MAX_RELS_ELEMENT_ATTRIBUTES`` attributes is refused as it starts.-- **In-process parsers have no timeout.** python-docx, python-pptx,- openpyxl, pandas and unstructured run inside the indexing worker with- no wall clock, so super-linear behaviour other than the fan-outs- listed above can pin a worker; only the soffice and pandoc- subprocesses carry timeouts.+- **Parse time and memory are bounded outside this guard.** On the+ upload path the final .docx/.pptx/.xlsx parse, and the HTML parse of+ a converted .odt/.epub, run in a child process+ (``security.isolated_loader``) with a 90-second deadline+ (``PARSE_TIMEOUT_SECONDS``) and, on Linux only, a soft 3 GiB+ data-memory limit (``MAX_CHILD_DATA_BYTES``, the soft ``RLIMIT_DATA``;+ not a whole-process memory ceiling); the soffice and pandoc conversions+ before it carry their own timeouts. Within those limits, super-linear+ behaviour other than the fan-outs listed above can still hold a+ parser slot until the deadline, and on other operating systems the+ parse has no memory limit."""from __future__ import annotationsdiff --git a/src/local_deep_research/security/isolated_loader.py b/src/local_deep_research/security/isolated_loader.pynew file mode 100644index 0000000000..1d7c59f00a--- /dev/null+++ b/src/local_deep_research/security/isolated_loader.py@@ -0,0 +1,430 @@+"""Bound the in-process document loaders after upload preflight/conversion.++The upload path has already checked ZIP containers and converted legacy+formats before calling this module. The worker runs only the final registered+loader. Parser output travels over a bounded pipe, never through a plaintext+temporary output file.+"""++from __future__ import annotations++import json+import os+import re+import signal+import subprocess+import sys+import threading+import time+from typing import Any++from langchain_core.documents import Document++from local_deep_research.config.unstructured_telemetry import (+ opt_out_of_unstructured_telemetry,+)+from local_deep_research.utilities.resource_utils import safe_close++from .isolated_metadata import metadata_from_output+++PARSE_TIMEOUT_SECONDS = 90+MAX_PROTOCOL_BYTES = 40_000_000+# Counted as the upload path joins the text (see joined_text_chars).+MAX_TEXT_CHARS = 10_000_000+MAX_DOCUMENTS = 10_000+# Metadata fields across the result, including empty values.+MAX_METADATA_FIELDS = 100_000+# Scan syntax before json.loads allocates collections. The protocol has a+# root object, a document array and two objects per document; reserve one+# additional collection per metadata field for the supported metadata types.+_JSON_SYNTAX = re.compile(rb'["\\{}\[\]:,]')+_MAX_JSON_DEPTH = 5+# Linux RLIMIT_DATA, soft limit only (see isolated_worker._cap_data_memory).+MAX_CHILD_DATA_BYTES = 3 * 1024 * 1024 * 1024+# The child's own CPU-time limit (POSIX). It ends a parse that outlives this+# process, as after a crash or kill here, when nothing enforces the deadline.+# The deadline ends a parse that uses one CPU first; the limit counts the CPU+# time of all the child's threads, so one using several can reach it first.+CHILD_CPU_SECONDS = PARSE_TIMEOUT_SECONDS + 30+MAX_CONCURRENT_PARSERS = 2+_parser_slots = threading.BoundedSemaphore(MAX_CONCURRENT_PARSERS)+# The NLTK data unstructured's text classification needs. The child never+# downloads it (see _run_capped). The Docker image ships it (Dockerfile,+# nltk-data stage, scripts/install_nltk_data.py); other installs install it+# once with NLTK_DATA_INSTALL_COMMAND.+NLTK_DATA_PACKAGES = ("punkt_tab", "averaged_perceptron_tagger_eng")+NLTK_DATA_INSTALL_COMMAND = "python -m nltk.downloader " + " ".join(+ NLTK_DATA_PACKAGES+)+# Shown for the file that needed the data. The official Docker image ships+# it, so this reaches source installs and images built some other way.+NLTK_DATA_MISSING_MESSAGE = (+ "NLTK data needed to parse this file is not installed on the server; "+ f"install it with: {NLTK_DATA_INSTALL_COMMAND} (run it as the user that "+ "runs the server; the official Docker image already includes this data)"+)++# Legacy Office and pandoc inputs are converted before this decision, so+# .doc/.ppt -> .docx/.pptx and .odt/.epub/.rtf/.rst/.org -> .html. Saved+# web archives (.mht/.mhtml) hold HTML parts that their loader parses+# with BeautifulSoup, the same class of work as an .html upload.+ISOLATED_FINAL_EXTENSIONS = frozenset(+ {+ ".docx",+ ".pptx",+ ".xlsx",+ ".xls",+ ".html",+ ".htm",+ ".mht",+ ".mhtml",+ ".md",+ ".markdown",+ ".eml",+ ".xml",+ ".enex",+ }+)+++class IsolatedLoaderError(ValueError):+ """A bounded document parse timed out, exceeded a limit, or failed."""+++class ParserBusyError(IsolatedLoaderError):+ """Every parser slot was in use; the same document can be retried."""+++class ParserDataMissingError(IsolatedLoaderError):+ """The parse needed NLTK data (NLTK_DATA_PACKAGES) that is not installed."""+++class ParserMemoryLimitError(IsolatedLoaderError):+ """The parse ran out of the child's data-memory limit."""+++class ParserResourceError(IsolatedLoaderError):+ """The child could not map a required parser library into memory."""+++def joined_text_chars(total: int, text: str) -> int:+ """Add *text* to *total*, counted as it appears in the joined text.++ ``extract_text_from_bytes`` joins the non-empty document texts with+ two-character separators, which ``bounded_pdf`` also counts for PDF+ pages. The worker and the parent both count this way, so the joined+ text of a bounded parse never exceeds ``MAX_TEXT_CHARS``.+ """+ if not text:+ return total+ return total + len(text) + (2 if total else 0)+++def _kill_tree(process: subprocess.Popen[bytes]) -> None:+ """Stop a parser and its converter/OCR descendants after a failure.++ On POSIX this kills the child's process group. A descendant that starts+ its own session leaves that group and is not killed here, so the+ isolated loaders must not start such helpers.+ """+ if os.name == "posix":+ try:+ os.killpg(process.pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ except OSError:+ if process.poll() is None:+ process.kill()+ else: # pragma: no cover - Windows only; no CI job runs this on Windows+ if process.poll() is None:+ try:+ subprocess.run(+ ["taskkill", "/F", "/T", "/PID", str(process.pid)],+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ timeout=5,+ check=False,+ )+ except (OSError, subprocess.TimeoutExpired):+ process.kill()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.kill()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ pass+++def _read_capped(pipe: Any, deadline: float) -> bytes:+ """Read a nonblocking raw pipe without waiting for a writer to close it."""+ output = bytearray()+ while True:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise IsolatedLoaderError("document parser timed out")+ try:+ chunk = pipe.read(+ min(64 * 1024, MAX_PROTOCOL_BYTES - len(output) + 1)+ )+ except (OSError, ValueError) as exc:+ raise IsolatedLoaderError(+ "document parser output could not be read"+ ) from exc+ if chunk is None:+ # RawIOBase.read returns None when a nonblocking pipe has no+ # bytes ready; b"" alone means EOF. No reader thread can remain+ # blocked holding a buffered stream lock during cleanup.+ time.sleep(min(0.01, remaining))+ continue+ if not chunk:+ return bytes(output)+ if len(output) + len(chunk) > MAX_PROTOCOL_BYTES:+ raise IsolatedLoaderError(+ "document parser output exceeded its limit"+ )+ output.extend(chunk)+++def _run_capped(command: list[str], timeout_s: float) -> bytes:+ """Read a child pipe with a hard wall clock and parent-side byte cap."""+ child_env = os.environ.copy()+ # OpenBLAS/OpenMP thread pools reserve large virtual arenas per worker.+ # One thread keeps the parser's memory budget meaningful and predictable.+ for name in (+ "OPENBLAS_NUM_THREADS",+ "OMP_NUM_THREADS",+ "MKL_NUM_THREADS",+ "NUMEXPR_NUM_THREADS",+ ):+ child_env[name] = "1"+ # Each child imports unstructured afresh, and its first unstructured+ # partition sends a usage request unless opted out. Package import sets+ # the opt-out too; this holds even if the server's environment changed.+ opt_out_of_unstructured_telemetry(child_env)+ # Importing unstructured downloads NLTK_DATA_PACKAGES when either is+ # missing, unless AUTO_DOWNLOAD_NLTK holds a value other than "true". In+ # the child that download would run under the parse deadline and outside+ # any egress policy, so it never runs there; a parse that needs the+ # missing data fails with ParserDataMissingError instead.+ child_env["AUTO_DOWNLOAD_NLTK"] = "false"+ # load_documents_isolated starts the child with -P to keep this+ # process's working directory off its sys.path, but an empty PYTHONPATH+ # entry (as in "src:" or ":src") is read as that directory. Drop empty+ # entries; named ones, relative ones included, keep their meaning.+ pythonpath = [+ entry+ for entry in child_env.get("PYTHONPATH", "").split(os.pathsep)+ if entry+ ]+ if pythonpath:+ child_env["PYTHONPATH"] = os.pathsep.join(pythonpath)+ else:+ child_env.pop("PYTHONPATH", None)+ try:+ process = subprocess.Popen( # noqa: S603 fixed executable and module argv+ command,+ env=child_env,+ stdin=subprocess.DEVNULL,+ stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL,+ bufsize=0,+ start_new_session=os.name == "posix",+ creationflags=(+ subprocess.CREATE_NEW_PROCESS_GROUP if os.name == "nt" else 0+ ),+ )+ except (OSError, ValueError) as exc:+ raise IsolatedLoaderError("document parser could not start") from exc+ if process.stdout is None:+ _kill_tree(process)+ raise IsolatedLoaderError("document parser pipe unavailable")+ deadline = time.monotonic() + timeout_s+ completed = False+ try:+ try:+ # Python 3.12+, our minimum version, supports this for pipes+ # on Windows as well as POSIX. Refuse if the OS cannot set it.+ os.set_blocking(process.stdout.fileno(), False)+ except (OSError, ValueError) as exc:+ raise IsolatedLoaderError(+ "document parser pipe could not be configured"+ ) from exc+ output = _read_capped(process.stdout, deadline)+ try:+ process.wait(timeout=max(0, deadline - time.monotonic()))+ except subprocess.TimeoutExpired as exc:+ raise IsolatedLoaderError("document parser timed out") from exc+ if process.returncode != 0:+ raise IsolatedLoaderError("document parser failed")+ completed = True+ return output+ finally:+ if not completed:+ _kill_tree(process)+ safe_close(process.stdout, "document parser pipe")+++def load_documents_isolated(+ input_path: str, extension: str, *, timeout_s: float = PARSE_TIMEOUT_SECONDS+) -> list[Document]:+ """Load a preflighted temporary document within time, memory and output caps."""+ if not 0 < timeout_s <= PARSE_TIMEOUT_SECONDS:+ raise ValueError("invalid document parser timeout")+ if extension not in ISOLATED_FINAL_EXTENSIONS:+ raise ValueError("extension does not require isolated parsing")+ # Upload rate limits allow bursts. Keep a slot through both child parsing+ # and parent-side result validation, whose JSON objects also use memory.+ # Refuse instead of waiting: uploads parse on the shared default+ # executor, so queued parses would hold threads other requests need.+ if not _parser_slots.acquire(blocking=False):+ raise ParserBusyError("document parser capacity reached")+ try:+ output = _run_capped(+ [+ sys.executable,+ # "-m" alone would put the server's working directory first+ # on the child's sys.path, so a module file there named like+ # one the parser imports would run in every parse. -P (3.11+)+ # leaves it off; PYTHONPATH (less its empty entries, see+ # _run_capped) and site-packages still apply.+ "-P",+ "-m",+ f"{__package__}.isolated_worker",+ input_path,+ extension,+ str(MAX_CHILD_DATA_BYTES),+ str(CHILD_CPU_SECONDS),+ # On Linux the child is killed when this process exits, and+ # does not parse if this process has already exited.+ str(os.getpid()),+ ],+ timeout_s,+ )+ return _documents_from_output(output, extension=extension)+ finally:+ _parser_slots.release()+++def _validate_protocol_structure(output: bytes) -> None:+ """Bound JSON collection allocation before decoding a worker result."""+ if len(output) > MAX_PROTOCOL_BYTES:+ raise IsolatedLoaderError("document parser output exceeded its limit")+ # The worker writes UTF-8. Raw NULs are not valid JSON text, and also+ # prevent an alternate UTF-16/32 encoding from bypassing this byte scan.+ if b"\0" in output:+ raise IsolatedLoaderError("document parser returned invalid output")+ max_collections = 2 + 2 * MAX_DOCUMENTS + MAX_METADATA_FIELDS+ max_tokens = 6 + 8 * MAX_DOCUMENTS + 12 * MAX_METADATA_FIELDS+ stack: list[int] = []+ in_string = False+ escaped_position = -1+ collections = tokens = 0+ for match in _JSON_SYNTAX.finditer(output):+ position = match.start()+ token = output[position]+ if in_string:+ if position == escaped_position:+ continue+ if token == 92: # backslash quotes the next byte+ escaped_position = position + 1+ elif token == 34:+ in_string = False+ continue+ if token == 34:+ in_string = True+ continue+ tokens += 1+ if token in (91, 123):+ stack.append(token)+ collections += 1+ if len(stack) > _MAX_JSON_DEPTH or collections > max_collections:+ raise IsolatedLoaderError(+ "document parser returned invalid documents"+ )+ elif token in (93, 125):+ if not stack or stack.pop() != (91 if token == 93 else 123):+ raise IsolatedLoaderError(+ "document parser returned invalid output"+ )+ if tokens > max_tokens:+ raise IsolatedLoaderError(+ "document parser returned invalid documents"+ )+++def _documents_from_output(+ output: bytes, *, extension: str | None = None+) -> list[Document]:+ """Validate the bounded worker result while its parser slot is held."""+ _validate_protocol_structure(output)+ try:+ payload = json.loads(output)+ except (UnicodeError, ValueError, RecursionError) as exc:+ # Deeply nested JSON exhausts the decoder's recursion limit; it is+ # malformed output like any other, not a server error.+ raise IsolatedLoaderError(+ "document parser returned invalid output"+ ) from exc+ if not isinstance(payload, dict) or payload.get("status") != "ok":+ if isinstance(payload, dict) and payload.get("kind") == "ImportError":+ raise ImportError("document parser dependency unavailable")+ if isinstance(payload, dict) and payload.get("kind") == "nltk_data":+ raise ParserDataMissingError(+ "document parser NLTK data is not installed"+ )+ if isinstance(payload, dict) and payload.get("kind") == "memory":+ raise ParserMemoryLimitError(+ "document parser exceeded its memory limit"+ )+ if isinstance(payload, dict) and payload.get("kind") == "resource":+ raise ParserResourceError(+ "document parser could not load its resources"+ )+ if (+ extension == ".enex"+ and isinstance(payload, dict)+ and payload.get("kind") == "DTDForbidden"+ ):+ from defusedxml.common import DTDForbidden++ raise DTDForbidden("en-export", None, None)+ raise IsolatedLoaderError("document parser refused the document")+ records = payload.get("documents")+ if not isinstance(records, list) or len(records) > MAX_DOCUMENTS:+ raise IsolatedLoaderError("document parser returned invalid documents")+ documents: list[Document] = []+ total_chars = 0+ metadata_fields = 0+ for record in records:+ if not isinstance(record, dict):+ raise IsolatedLoaderError(+ "document parser returned invalid documents"+ )+ content, metadata = record.get("page_content"), record.get("metadata")+ # String metadata is the default. Evernote also returns dates,+ # optional values and tags, which have an explicit wire format.+ if not isinstance(content, str) or not isinstance(metadata, dict):+ raise IsolatedLoaderError(+ "document parser returned invalid documents"+ )+ metadata_fields += len(metadata)+ if metadata_fields > MAX_METADATA_FIELDS:+ raise IsolatedLoaderError(+ "document parser output exceeded its limit"+ )+ try:+ metadata = metadata_from_output(metadata, extension)+ except ValueError as exc:+ raise IsolatedLoaderError(+ "document parser returned invalid documents"+ ) from exc+ total_chars = joined_text_chars(total_chars, content)+ if total_chars > MAX_TEXT_CHARS:+ raise IsolatedLoaderError(+ "document parser output exceeded its limit"+ )+ documents.append(Document(page_content=content, metadata=metadata))+ return documentsdiff --git a/src/local_deep_research/security/isolated_metadata.py b/src/local_deep_research/security/isolated_metadata.pynew file mode 100644index 0000000000..f9c0c254bd--- /dev/null+++ b/src/local_deep_research/security/isolated_metadata.py@@ -0,0 +1,60 @@+"""The metadata values supported by the upload parser's JSON protocol."""++from time import struct_time+from typing import Any+++def metadata_for_output(metadata: dict[str, Any], extension: str) -> dict:+ """Encode the registered loaders' metadata without arbitrary objects."""+ result = {}+ for key, value in metadata.items():+ if not isinstance(key, str):+ raise ValueError("invalid parser metadata key")+ if isinstance(value, str):+ result[key] = value+ elif extension == ".enex" and value is None:+ result[key] = None+ elif (+ extension == ".enex"+ and key in {"created", "updated"}+ and isinstance(value, struct_time)+ ):+ result[key] = list(value)+ elif (+ extension == ".enex"+ and key == "tag"+ and isinstance(value, list)+ and all(isinstance(tag, str) for tag in value)+ ):+ result[key] = value+ else:+ raise ValueError("invalid parser metadata value")+ return result+++def metadata_from_output(metadata: dict, extension: str | None) -> dict:+ """Restore Evernote dates and retain the existing string-only contract."""+ result = {}+ for key, value in metadata.items():+ if isinstance(value, str):+ result[key] = value+ elif extension == ".enex" and value is None:+ result[key] = None+ elif (+ extension == ".enex"+ and key in {"created", "updated"}+ and isinstance(value, list)+ and len(value) == 9+ and all(type(part) is int for part in value)+ ):+ result[key] = struct_time(value)+ elif (+ extension == ".enex"+ and key == "tag"+ and isinstance(value, list)+ and all(isinstance(tag, str) for tag in value)+ ):+ result[key] = value+ else:+ raise ValueError("invalid parser metadata value")+ return resultdiff --git a/src/local_deep_research/security/isolated_worker.py b/src/local_deep_research/security/isolated_worker.pynew file mode 100644index 0000000000..45d93a9195--- /dev/null+++ b/src/local_deep_research/security/isolated_worker.py@@ -0,0 +1,263 @@+"""Child entry point for a bounded upload document parse.++Only the already-preflighted, already-converted temporary input path is+accepted from the parent, with the limits to apply and the parent's process+ID. Parser stdout/stderr never reaches the protocol pipe; the pipe carries+one bounded JSON result and is not stored on disk.+"""++from __future__ import annotations++import json+import os+import signal+import sys+from typing import Any++# SIGXCPU's default action ends the process. Code that catches it still gets+# SIGKILL at the hard limit, this many seconds of CPU time later.+_CPU_KILL_GRACE_SECONDS = 5+_PR_SET_PDEATHSIG = 1 # from <linux/prctl.h>+# Encoded before any limit applies, so reporting a memory refusal needs no+# new allocation once the data limit is reached.+_MEMORY_RESULT = b'{"status": "error", "kind": "memory"}'++# langchain_core imports this package only for BaseLoader.load_and_split,+# which the worker never calls, and treats it as optional. Importing it+# also imports sentence-transformers, transformers and torch, which adds+# seconds and hundreds of MB to every parse. A None entry in sys.modules+# makes that import raise ImportError, which langchain_core handles.+_UNUSED_PACKAGES = ("langchain_text_splitters",)+++def _skip_unused_imports() -> None:+ for name in _UNUSED_PACKAGES:+ sys.modules.setdefault(name, None) # type: ignore[arg-type]+++def _exit_with_parent(parent_pid: int) -> None:+ # Linux only. A parent that crashed or was killed no longer stops this+ # parse at its deadline, and a restarted server's slots do not count it,+ # so ask the kernel to SIGKILL this child when its parent exits. The+ # kernel sends the signal when the parent *thread* that started the child+ # exits; that thread waits in _run_capped until this child has exited.+ if sys.platform != "linux":+ return+ try:+ import ctypes++ ctypes.CDLL(None, use_errno=True).prctl(+ _PR_SET_PDEATHSIG,+ ctypes.c_ulong(signal.SIGKILL),+ ctypes.c_ulong(0),+ ctypes.c_ulong(0),+ ctypes.c_ulong(0),+ )+ except (ImportError, OSError, AttributeError):+ # No ctypes, no C library or no prctl in it: the CPU-time limit+ # still ends a parse that outlives its parent.+ pass+ # A parent that exited before that request sends no signal, and nothing+ # would read the result. The parent starts this interpreter directly+ # (sys.executable), so while it lives it is this process's parent.+ if os.getppid() != parent_pid:+ raise OSError("document parser's parent process has exited")+++def _limit_cpu_time(seconds: int) -> None:+ # POSIX only. The parent's deadline stops a parse while the parent lives;+ # this limit stops one that outlives it: SIGXCPU after *seconds* of CPU+ # time, SIGKILL at the hard limit. The hard limit is lowered as well, so+ # code in the child cannot raise either limit again.+ if os.name != "posix":+ return+ if seconds < 1:+ raise ValueError("invalid CPU-time limit")+ import resource++ # SIGXCPU's default action also dumps core, which would write the+ # parser's memory, document text included, to disk.+ resource.setrlimit(resource.RLIMIT_CORE, (0, 0))+ soft, hard = resource.getrlimit(resource.RLIMIT_CPU)+ hard_cap = seconds + _CPU_KILL_GRACE_SECONDS+ if hard != resource.RLIM_INFINITY:+ hard_cap = min(hard, hard_cap)+ soft_cap = min(seconds, hard_cap)+ if soft != resource.RLIM_INFINITY:+ soft_cap = min(soft, soft_cap)+ resource.setrlimit(resource.RLIMIT_CPU, (soft_cap, hard_cap))+++def _cap_data_memory(target: int) -> None:+ # This limit also covers anonymous mmap on supported Linux kernels.+ # Only the soft limit is lowered, so it is a soft limit: code in the+ # child could raise it back to the hard limit. The child runs only the+ # registered loaders. It counts the data segment and private writable+ # mappings (VmData), not the stack or read-only and shared mappings.+ if sys.platform != "linux":+ return+ import resource++ soft, hard = resource.getrlimit(resource.RLIMIT_DATA)+ cap = min(+ target,+ soft if soft != resource.RLIM_INFINITY else target,+ hard if hard != resource.RLIM_INFINITY else target,+ )+ resource.setrlimit(resource.RLIMIT_DATA, (cap, hard))+ resource.setrlimit(resource.RLIMIT_CORE, (0, 0))+++def _is_missing_nltk_data(+ exc: BaseException, packages: tuple[str, ...]+) -> bool:+ # nltk.data.find raises a plain LookupError (not KeyError or another+ # subclass) that names the resource it could not find. The child never+ # downloads that data, so the parent can tell the operator to install it.+ return type(exc) is LookupError and any(+ package in str(exc) for package in packages+ )+++def _import_failure_kind(exc: ImportError) -> str:+ # The dynamic linker reports an unavailable mapping as ImportError,+ # even when the dependency exists. Do not report it as an absent package.+ detail = str(exc).lower()+ if "cannot allocate memory" in detail or "not enough memory" in detail:+ return "memory"+ if "failed to map segment" in detail:+ return "resource"+ return "ImportError"+++def _result(path: str, extension: str) -> dict[str, Any]:+ from .isolated_loader import (+ MAX_DOCUMENTS,+ MAX_METADATA_FIELDS,+ MAX_PROTOCOL_BYTES,+ MAX_TEXT_CHARS,+ NLTK_DATA_PACKAGES,+ joined_text_chars,+ )+ from local_deep_research.document_loaders.loader_registry import (+ get_loader_class_for_extension,+ )+ from .isolated_metadata import metadata_for_output++ # The parent's openpyxl patch is process-local. Reapply it before the+ # child loads any spreadsheet, or chartsheet drawings can multiply image+ # reads after the parent's ZIP guard has approved the package.+ if extension == ".xlsx":+ from local_deep_research.document_loaders.openpyxl_hardening import (+ disable_openpyxl_drawing_reads,+ )++ if not disable_openpyxl_drawing_reads():+ return {"status": "error", "kind": "guard"}++ loader_info = get_loader_class_for_extension(extension)+ if loader_info is None:+ return {"status": "error", "kind": "unsupported"}+ loader_class, loader_kwargs = loader_info+ try:+ documents = loader_class(path, **loader_kwargs).load()+ except ImportError as exc:+ return {"status": "error", "kind": _import_failure_kind(exc)}+ except MemoryError:+ # The data limit, not a document the parser could not read; main()+ # reports it as such.+ raise+ except Exception as exc:+ if extension == ".enex":+ from defusedxml.common import DTDForbidden++ if isinstance(exc, DTDForbidden):+ return {"status": "error", "kind": "DTDForbidden"}+ if _is_missing_nltk_data(exc, NLTK_DATA_PACKAGES):+ return {"status": "error", "kind": "nltk_data"}+ return {"status": "error", "kind": "parser"}++ if len(documents) > MAX_DOCUMENTS:+ return {"status": "error", "kind": "limit"}+ total_chars = 0+ metadata_fields = 0+ records = []+ for doc in documents:+ content = doc.page_content+ if not isinstance(content, str):+ return {"status": "error", "kind": "parser"}+ total_chars = joined_text_chars(total_chars, content)+ if total_chars > MAX_TEXT_CHARS:+ return {"status": "error", "kind": "limit"}+ metadata_fields += len(doc.metadata)+ if metadata_fields > MAX_METADATA_FIELDS:+ return {"status": "error", "kind": "limit"}+ try:+ metadata = metadata_for_output(doc.metadata, extension)+ except ValueError:+ return {"status": "error", "kind": "parser"}+ records.append({"page_content": content, "metadata": metadata})++ answer = {"status": "ok", "documents": records}+ # The parent has an independent cap, but refuse oversized output before+ # writing any part of the result to its pipe.+ encoded = json.dumps(answer, ensure_ascii=False, default=str).encode(+ "utf-8"+ )+ if len(encoded) > MAX_PROTOCOL_BYTES:+ return {"status": "error", "kind": "limit"}+ return answer+++def main() -> int:+ # Before any loader import; tests call _result in their own process.+ _skip_unused_imports()+ # Preserve a separate pipe descriptor for the protocol, then redirect+ # ordinary stdout. Native parser libraries can print document content+ # directly to fd 1, so redirecting only sys.stdout is insufficient.+ protocol_fd = os.dup(1)+ devnull_fd = os.open(os.devnull, os.O_WRONLY)+ os.dup2(devnull_fd, 1)+ os.close(devnull_fd)+ try:+ out_of_memory = False+ result: dict[str, Any] | None = None+ if len(sys.argv) != 6:+ result = {"status": "error", "kind": "arguments"}+ else:+ path, extension, data_cap, cpu_seconds, parent_pid = sys.argv[1:]+ try:+ # Before the parser runs, so no parse outlives its parent or+ # escapes these limits.+ _exit_with_parent(int(parent_pid))+ _limit_cpu_time(int(cpu_seconds))+ _cap_data_memory(int(data_cap))+ result = _result(path, extension)+ except MemoryError:+ # Leaving this block drops the traceback and the parser+ # objects it holds before anything new is allocated.+ out_of_memory = True+ except ImportError as exc:+ result = {"status": "error", "kind": _import_failure_kind(exc)}+ except (OSError, ValueError):+ result = {"status": "error", "kind": "limit"}+ except Exception:+ result = {"status": "error", "kind": "parser"}+ encoded = _MEMORY_RESULT+ if not out_of_memory:+ try:+ encoded = json.dumps(+ result, ensure_ascii=False, default=str+ ).encode("utf-8")+ except MemoryError:+ encoded = _MEMORY_RESULT+ remaining = memoryview(encoded)+ while remaining:+ remaining = remaining[os.write(protocol_fd, remaining) :]+ return 0+ finally:+ os.close(protocol_fd)+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.pyindex fb11993207..b7315676b4 100644--- a/src/local_deep_research/web/routers/rag.py+++ b/src/local_deep_research/web/routers/rag.py@@ -2779,6 +2779,11 @@ def _upload_to_collection_sync(extract_text_from_bytes,is_extension_supported,)+ from ...security.isolated_loader import (+ NLTK_DATA_MISSING_MESSAGE,+ ParserBusyError,+ ParserDataMissingError,+ )file_extension = Path(filename).suffix.lower()@@ -2808,9 +2813,34 @@ def _upload_to_collection_sync(sp.commit()sp = Nonedb_session.commit()- extracted_text = extract_text_from_bytes(- file_content, file_extension, filename- )+ try:+ extracted_text = extract_text_from_bytes(+ file_content, file_extension, filename+ )+ except ParserBusyError:+ # Every bounded parser slot was serving another+ # upload. Unlike an unreadable file, this one can+ # succeed when uploaded again, so say so. No+ # SAVEPOINT is open here.+ errors.append(+ {+ "filename": filename,+ "error": "Document parser busy with other uploads; upload this file again",+ }+ )+ continue+ except ParserDataMissingError:+ # The parser child never downloads NLTK data, and+ # this server lacks the data the parse needed. The+ # file may be fine; tell the operator the fix. No+ # SAVEPOINT is open here.+ errors.append(+ {+ "filename": filename,+ "error": NLTK_DATA_MISSING_MESSAGE,+ }+ )+ continue# Keep write failures isolated to this file after the# parser returns, using a fresh database snapshot.sp = db_session.begin_nested()diff --git a/tests/ci/standalone/verify_upload_parser.py b/tests/ci/standalone/verify_upload_parser.pynew file mode 100644index 0000000000..1f7940ad09--- /dev/null+++ b/tests/ci/standalone/verify_upload_parser.py@@ -0,0 +1,46 @@+"""Check the production image's NLTK data and normal upload parser offline."""++import io++import nltk+from docx import Document++from local_deep_research.document_loaders import load_from_bytes+++def main() -> None:+ # Both resources must be usable by the service user, with no download.+ sentence = nltk.sent_tokenize("Otters build dams.")[0]+ assert nltk.pos_tag(nltk.word_tokenize(sentence))+ document = Document()+ document.add_paragraph("Production parser round trip.")+ source = io.BytesIO()+ document.save(source)+ records = load_from_bytes(source.getvalue(), ".docx", "check.docx")+ assert [record.page_content for record in records] == [+ "Production parser round trip."+ ]+ assert records[0].metadata["original_filename"] == "check.docx"+ for extension, source in {+ ".md": b"# Check\n\nProduction parser round trip.",+ ".xml": b"<root><p>Production parser round trip.</p></root>",+ ".eml": (+ b"From: [email protected]\nTo: [email protected]\n"+ b"Subject: Check\nContent-Type: text/html\n\n"+ b"<p>Production parser round trip.</p>"+ ),+ ".enex": (+ b"<en-export><note><content><![CDATA[<en-note><p>"+ b"Production parser round trip."+ b"</p></en-note>]]></content></note></en-export>"+ ),+ }.items():+ records = load_from_bytes(source, extension, f"check{extension}")+ assert "Production parser round trip." in "\n".join(+ record.page_content for record in records+ )+ print("Upload parser check passed")+++if __name__ == "__main__":+ main()diff --git a/tests/config/test_unstructured_telemetry.py b/tests/config/test_unstructured_telemetry.pynew file mode 100644index 0000000000..4c47a92e6e--- /dev/null+++ b/tests/config/test_unstructured_telemetry.py@@ -0,0 +1,91 @@+"""unstructured's import-time usage request must stay off in LDR processes."""++import json+import os+import subprocess+import sys++from local_deep_research.config.unstructured_telemetry import (+ opt_out_of_unstructured_telemetry,+)++TELEMETRY_URL_PREFIX = "https://packages.unstructured.io/python-telemetry?"++# Runs in a fresh interpreter, where unstructured has not been imported yet.+# requests.get only records, so nothing is sent whichever way this goes.+CHILD_SCRIPT = """+import json, os, sys++import requests++calls = []+requests.get = lambda *args, **kwargs: calls.append(+ args[0] if args else kwargs.get("url")+)++report_path, import_ldr_first = sys.argv[1], sys.argv[2] == "yes"+if import_ldr_first:+ import local_deep_research+import unstructured.logger++with open(report_path, "w") as handle:+ json.dump(+ {"calls": calls, "opt_out": os.environ.get("SCARF_NO_ANALYTICS")},+ handle,+ )+"""+++def _import_unstructured_logger(tmp_path, *, import_ldr_first):+ # Importing LDR in this process already set the opt-out, so the child+ # must not inherit it: it starts with neither opt-out variable set.+ report = tmp_path / "report.json"+ env = {+ name: value+ for name, value in os.environ.items()+ if name not in ("SCARF_NO_ANALYTICS", "DO_NOT_TRACK")+ }+ result = subprocess.run(+ [+ sys.executable,+ "-c",+ CHILD_SCRIPT,+ str(report),+ "yes" if import_ldr_first else "no",+ ],+ env=env,+ check=False,+ capture_output=True,+ timeout=120,+ )+ assert result.returncode == 0, result.stderr[-2000:]+ return json.loads(report.read_text())+++def test_opt_out_overwrites_a_value_unstructured_does_not_honour():+ # unstructured opts out only on exactly "true", so "1" would still send+ # the request. DO_NOT_TRACK is not touched: other libraries read it.+ env = {"SCARF_NO_ANALYTICS": "1", "DO_NOT_TRACK": "1"}+ opt_out_of_unstructured_telemetry(env)+ assert env == {"SCARF_NO_ANALYTICS": "true", "DO_NOT_TRACK": "1"}+++def test_importing_ldr_opts_out_before_unstructured_is_imported(tmp_path):+ # The server, or any program that imports LDR, imports unstructured+ # lazily, at its first unstructured-backed parse. A fresh interpreter+ # that imports LDR first and unstructured.logger second stands in for+ # one.+ assert _import_unstructured_logger(tmp_path, import_ldr_first=True) == {+ "calls": [],+ "opt_out": "true",+ }+++def test_unstructured_sends_the_request_without_the_opt_out(tmp_path):+ # Control for the test above: without LDR, the same recording sees the+ # request. If unstructured stopped sending it through requests.get, the+ # test above would pass without proving anything; this one fails then.+ report = _import_unstructured_logger(tmp_path, import_ldr_first=False)+ assert report["opt_out"] is None+ assert len(report["calls"]) == 1+ assert report["calls"][0].startswith(TELEMETRY_URL_PREFIX)diff --git a/tests/conftest.py b/tests/conftest.pyindex 6acf1d69f5..43065dac84 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -5,7 +5,7 @@ import tempfileimport typesimport shutilimport uuid-from contextlib import suppress+from contextlib import contextmanager, suppressfrom pathlib import Pathfrom unittest.mock import Mock, patch@@ -226,6 +226,13 @@ def pytest_configure(config):# For local testing, set it here if not already setif not os.environ.get("LDR_TESTING_WITH_MOCKS"):os.environ["LDR_TESTING_WITH_MOCKS"] = "true"+ # Unless AUTO_DOWNLOAD_NLTK holds a value other than "true", importing+ # unstructured.nlp.tokenize, as unstructured's text partitioners do,+ # downloads the NLTK data they classify text with if any of it is+ # missing. That download would write the data directory all xdist+ # workers share without nltk_parser_data's lock, so tests get the data+ # from that autouse fixture alone.+ os.environ["AUTO_DOWNLOAD_NLTK"] = "false"@pytest.fixture(scope="session", autouse=True)@@ -257,6 +264,123 @@ def no_readability_node_subprocess():readability_extractor.NODE_TIMEOUT_SECONDS = original+# Run by nltk_parser_data in a separate interpreter. The check tokenizes and+# tags a sentence, as unstructured's text classification does, so a package+# that an interrupted download left incomplete counts as missing. The exit+# status is 0 only if the data passed that check. When it fails, the script+# downloads the packages named as arguments, if any: nltk.download compares+# each package with the size and checksum in its index and downloads it+# again if they differ.+_INSTALL_NLTK_PARSER_DATA = """+import sys++import nltk+++def usable():+ try:+ sentence = nltk.sent_tokenize("Otters build dams.")[0]+ nltk.pos_tag(nltk.word_tokenize(sentence))+ except Exception:+ return False+ return True+++if not usable():+ for package in sys.argv[1:]:+ nltk.download(package, quiet=True)+ sys.exit(1)+"""+++@contextmanager+def _file_lock(path, *, exclusive):+ """Hold a lock on *path* that other processes wait for.++ A shared lock waits only for an exclusive one; an exclusive lock waits+ for every other lock on the file.+ """+ try:+ import fcntl+ except ImportError: # Windows: no flock; processes there do not wait+ yield+ return+ with open(path, "a") as handle:+ fcntl.flock(handle, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)+ try:+ yield+ finally:+ fcntl.flock(handle, fcntl.LOCK_UN)++[email protected](scope="session", autouse=True)+def nltk_parser_data(tmp_path_factory):+ """Install the NLTK data that unstructured classifies text with.++ The parser child never downloads NLTK data (AUTO_DOWNLOAD_NLTK=false,+ see security/isolated_loader.py), and pytest_configure turns+ unstructured's import-time download off in every test process too. So+ this fixture, which installs the data as an operator would, is the only+ way tests get it. It is autouse and session-scoped: each test process+ (each xdist worker, or the one process without xdist) runs it once,+ while setting up its first test, so every test under tests/ runs after+ it, whether its parse runs in a parser child or in this process.++ The xdist workers of a session share one data directory (by default+ ~/nltk_data) and one lock file. Each worker first checks the data while+ holding the lock shared, so the checks run at the same time and wait+ only for a worker that holds it exclusively. If the data is usable, that+ check, a few seconds spent mostly importing nltk, is all this fixture+ does. Otherwise the worker takes the lock exclusively, checks again and+ downloads what is missing, so no two workers write the directory at once+ and no check reads a package another worker is still unpacking. Checks+ and downloads run in a separate interpreter, so this process does not+ load the data. pytest-timeout counts this fixture, waits included,+ against each worker's first test, so a check has 20 seconds and a check+ with a download 75. Without network, parses that need the data fail:+ in a parser child with ParserDataMissingError, in this process with+ LookupError.+ """+ import subprocess++ # The pytest-xdist recipe: every worker's base temporary directory is+ # inside this one, which the whole session shares.+ lock = tmp_path_factory.getbasetemp().parent / "nltk_parser_data.lock"+ env = {+ **os.environ,+ "AUTO_DOWNLOAD_NLTK": "false",+ "SCARF_NO_ANALYTICS": "true",+ }++ def data_usable(*download, timeout):+ # Run the script, which downloads the packages in *download* if the+ # data fails its check. True only if the data passed the check.+ try:+ completed = subprocess.run(+ [sys.executable, "-c", _INSTALL_NLTK_PARSER_DATA, *download],+ env=env,+ check=False,+ capture_output=True,+ timeout=timeout,+ )+ except (OSError, subprocess.TimeoutExpired):+ return False+ return completed.returncode == 0++ with _file_lock(lock, exclusive=False):+ if data_usable(timeout=20):+ return++ from local_deep_research.security.isolated_loader import (+ NLTK_DATA_PACKAGES,+ )++ # Another worker may have installed the data while this one waited for+ # the lock, so the script checks again before it downloads anything.+ with _file_lock(lock, exclusive=True):+ data_usable(*NLTK_DATA_PACKAGES, timeout=75)++@pytest.fixture(autouse=True)def skip_if_no_real_llm(request):"""Skip tests marked with @pytest.mark.requires_llm when running with mocks."""diff --git a/tests/deployment/test_nltk_data_in_image.py b/tests/deployment/test_nltk_data_in_image.pynew file mode 100644index 0000000000..1bc5a91de0--- /dev/null+++ b/tests/deployment/test_nltk_data_in_image.py@@ -0,0 +1,258 @@+"""The Docker image ships the NLTK data the bounded upload parser needs.++The parser child sets ``AUTO_DOWNLOAD_NLTK=false`` (isolated_loader), so+unstructured's Word, PowerPoint, ``.xlsx`` and HTML text classification+finds ``punkt_tab`` and ``averaged_perceptron_tagger_eng`` installed or the+upload fails. These static checks pin how the image gets that data without+building it: the ``nltk-data`` stage runs scripts/install_nltk_data.py, and+the ``ldr`` stage copies the result to a directory on NLTK's default search+path, readable by ``ldruser``. The script itself is exercised offline with+archives built here.+"""++from __future__ import annotations++import hashlib+import importlib.util+import io+import re+import stat+import zipfile+from pathlib import Path++import pytest++from local_deep_research.security import isolated_loader++REPO_ROOT = Path(__file__).resolve().parents[2]+DOCKERFILE = REPO_ROOT / "Dockerfile"+SCRIPT = REPO_ROOT / "scripts" / "install_nltk_data.py"+# On NLTK's default nltk.data.path on every non-Windows host, for every user.+IMAGE_NLTK_DATA = "/usr/local/share/nltk_data"+++def _load_script():+ spec = importlib.util.spec_from_file_location("install_nltk_data", SCRIPT)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def _logical_lines(text: str) -> list[str]:+ # Docker drops comment lines, also inside a continued instruction, and+ # joins lines that end in a backslash.+ lines, current = [], ""+ for raw in text.splitlines():+ stripped = raw.strip()+ if stripped.startswith("#") or (not stripped and current):+ continue+ if stripped.endswith("\\"):+ current += stripped[:-1] + " "+ continue+ current += stripped+ if current.strip():+ lines.append(current.strip())+ current = ""+ return lines+++def _stages() -> list[tuple[str, list[tuple[str, str]]]]:+ stages: list[tuple[str, list[tuple[str, str]]]] = []+ for line in _logical_lines(DOCKERFILE.read_text()):+ keyword, _, argument = line.partition(" ")+ keyword = keyword.upper()+ if keyword == "FROM":+ words = argument.split()+ name = words[2] if len(words) == 3 else f"#{len(stages)}"+ stages.append((name.lower(), []))+ elif stages:+ stages[-1][1].append((keyword, argument.strip()))+ return stages+++def _stage(name: str) -> list[tuple[str, str]]:+ found = [body for stage, body in _stages() if stage == name]+ assert len(found) == 1, f"expected one {name!r} stage"+ return found[0]+++def test_script_installs_exactly_the_packages_the_parser_needs():+ script = _load_script()+ assert (+ tuple(package.name for package in script.PACKAGES)+ == isolated_loader.NLTK_DATA_PACKAGES+ )+ # unstructured looks each one up in a fixed category. Read its source+ # rather than import it: importing it downloads missing data.+ spec = importlib.util.find_spec("unstructured.nlp.tokenize")+ if spec is None or spec.origin is None:+ pytest.skip("unstructured is not installed")+ source = " ".join(Path(spec.origin).read_text().split())+ for package in script.PACKAGES:+ assert (+ f'package_category="{package.subdir}", '+ f'package_name="{package.name}"' in source+ ) or (+ f'package_name="{package.name}", '+ f'package_category="{package.subdir}"' in source+ ), f"unstructured no longer looks up {package.subdir}/{package.name}"+++def test_script_pins_a_commit_and_every_archive_hash():+ script = _load_script()+ assert re.fullmatch(r"[0-9a-f]{40}", script.NLTK_DATA_COMMIT)+ for package in script.PACKAGES:+ assert re.fullmatch(r"[0-9a-f]{64}", package.sha256)+ assert package.size > 0+ url = script.package_url(package)+ assert url.startswith("https://raw.githubusercontent.com/nltk/")+ assert f"/{script.NLTK_DATA_COMMIT}/" in url+ assert "gh-pages" not in url+++def test_dockerfile_builds_the_data_and_ships_it_to_the_ldr_stage():+ stages = [name for name, _ in _stages()]+ # ldr is what `docker build` builds without --target, and it can only+ # copy from a stage defined before it.+ assert stages[-1] == "ldr"+ assert stages.index("nltk-data") < stages.index("ldr")++ builder = _stage("nltk-data")+ copies = [arg for keyword, arg in builder if keyword == "COPY"]+ assert copies == ["scripts/install_nltk_data.py /tmp/install_nltk_data.py"]+ runs = [arg for keyword, arg in builder if keyword == "RUN"]+ assert any(+ re.match(r"python3 -I /tmp/install_nltk_data\.py /nltk_data(\s|$)", run)+ for run in runs+ ), runs++ ldr = _stage("ldr")+ shipped = [+ arg+ for keyword, arg in ldr+ if keyword == "COPY" and "--from=nltk-data" in arg.split()+ ]+ # No --chown: the data stays root-owned and read-only to ldruser.+ assert shipped == [f"--from=nltk-data /nltk_data/ {IMAGE_NLTK_DATA}/"]+ # NLTK_DATA would add a path; the default one must stay in effect.+ assert not any(+ keyword == "ENV" and "NLTK_DATA" in arg for keyword, arg in ldr+ )+++def test_image_directory_is_on_nltks_default_search_path():+ # nltk/data.py lists the default directories; read rather than import.+ spec = importlib.util.find_spec("nltk")+ if spec is None or not spec.submodule_search_locations:+ pytest.skip("nltk is not installed")+ data_py = Path(next(iter(spec.submodule_search_locations))) / "data.py"+ assert f'"{IMAGE_NLTK_DATA}"' in data_py.read_text()+++def test_production_images_run_the_parser_check_offline_as_the_service_user():+ import yaml++ workflow = yaml.safe_load(+ (REPO_ROOT / ".github/workflows/docker-tests.yml").read_text()+ )+ job = workflow["jobs"]["ldr-production-smoke-test"]+ checks = [+ step+ for step in job["steps"]+ if step.get("name")+ == "Verify upload parser and NLTK data offline as service user"+ ]+ assert len(checks) == 1+ assert "if" not in checks[0]+ command = checks[0]["run"]+ for setting in (+ "timeout 120s docker run",+ "--network none",+ "--user ldruser",+ "AUTO_DOWNLOAD_NLTK=false",+ "verify_upload_parser.py",+ "--entrypoint /install/.venv/bin/python",+ ):+ assert setting in command+ assert {item["arch"] for item in job["strategy"]["matrix"]["include"]} == {+ "amd64",+ "arm64",+ }+++def _zip(members: dict[str, bytes | None], symlink: str | None = None) -> bytes:+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w") as bundle:+ for name, data in members.items():+ if data is None:+ bundle.writestr(name, b"")+ else:+ bundle.writestr(name, data)+ if symlink:+ info = zipfile.ZipInfo(symlink)+ info.external_attr = (stat.S_IFLNK | 0o777) << 16+ bundle.writestr(info, "/etc/passwd")+ return buffer.getvalue()+++ ("members", "symlink"),+ [+ ({"punkt_tab/../../escaped": b"x"}, None),+ ({"/tmp/absolute": b"x"}, None),+ ({"other/file": b"x"}, None),+ ({"punkt_tab\\..\\escaped": b"x"}, None),+ ({"punkt_tab/ok": b"x"}, "punkt_tab/link"),+ ],+ ids=["dotdot", "absolute", "other-package", "backslash", "symlink"],+)+def test_script_refuses_unsafe_archive_members(tmp_path, members, symlink):+ script = _load_script()+ package = script.Package("tokenizers", "punkt_tab", 0, "")+ with pytest.raises(ValueError, match="unsafe archive member"):+ script.extract(package, _zip(members, symlink), tmp_path)+ assert list(tmp_path.iterdir()) == []+++def test_script_refuses_an_archive_whose_hash_or_size_differs():+ script = _load_script()+ package = script.PACKAGES[0]+ with pytest.raises(ValueError, match="SHA-256"):+ script.verify(package, b"\0" * package.size)+ with pytest.raises(ValueError, match="bytes"):+ script.verify(package, b"\0" * (package.size + 1))+++def test_script_installs_verified_archives_where_nltk_looks(tmp_path):+ script = _load_script()+ archives = {+ "punkt_tab": _zip(+ {"punkt_tab/": None, "punkt_tab/english/sent_starters.txt": b"x"}+ ),+ "averaged_perceptron_tagger_eng": _zip(+ {"averaged_perceptron_tagger_eng/weights.json": b"{}"}+ ),+ }+ script.PACKAGES = tuple(+ package._replace(+ size=len(archives[package.name]),+ sha256=hashlib.sha256(archives[package.name]).hexdigest(),+ )+ for package in script.PACKAGES+ )+ requested = []++ def fetcher(url, limit):+ requested.append(url)+ return archives[url.rsplit("/", 1)[1].removesuffix(".zip")]++ script.install(tmp_path, fetcher)+ assert requested == [script.package_url(p) for p in script.PACKAGES]+ data = tmp_path / "tokenizers" / "punkt_tab" / "english"+ tagger = tmp_path / "taggers" / "averaged_perceptron_tagger_eng"+ assert (data / "sent_starters.txt").read_bytes() == b"x"+ assert (tagger / "weights.json").read_bytes() == b"{}"+ # Readable and traversable by every user, writable only by the owner.+ assert stat.S_IMODE((data / "sent_starters.txt").stat().st_mode) == 0o644+ assert stat.S_IMODE(data.stat().st_mode) == 0o755+ assert stat.S_IMODE(tmp_path.stat().st_mode) == 0o755diff --git a/tests/document_loaders/test_loader_hostile_input.py b/tests/document_loaders/test_loader_hostile_input.pyindex 60190eff98..47e9317cf1 100644--- a/tests/document_loaders/test_loader_hostile_input.py+++ b/tests/document_loaders/test_loader_hostile_input.py@@ -661,8 +661,24 @@ class TestNestingAndAmplificationBounds:f"alias expansion amplified {len(text) / len(payload):.1f}x")- def test_xml_entity_amplification_is_capped_by_the_parser(self):+ def test_xml_entity_amplification_is_capped_inside_the_bounded_child(+ self, tmp_path+ ):+ """lxml's amplification cap still refuses the bomb, now in the child.++ ``.xml`` is parsed by the bounded child process+ (``ISOLATED_FINAL_EXTENSIONS``), so the ``XMLSyntaxError`` lxml+ raises no longer reaches the caller: the child reports a parser+ failure and the caller sees the generic refusal. The first assertion+ pins the cap itself on the registered loader class, so this test+ still fails if the parser stops refusing the bomb; the second pins+ that the refusal crosses the boundary as a plain refusal rather than+ a limit, memory, busy or missing-NLTK-data error.+ """etree = pytest.importorskip("lxml.etree")+ from local_deep_research.security.isolated_loader import (+ IsolatedLoaderError,+ )def entity_bomb(levels, fan):entities = ['<!ENTITY e0 "xxxxxxxxxx">']@@ -677,9 +693,19 @@ class TestNestingAndAmplificationBounds:payload = entity_bomb(6, 10)assert len(payload) < 1024- with pytest.raises(etree.XMLSyntaxError) as excinfo:++ loader_info = loader_registry.get_loader_class_for_extension(".xml")+ assert loader_info is not None+ loader_class, loader_kwargs = loader_info+ bomb_path = tmp_path / "bomb.xml"+ bomb_path.write_bytes(payload)+ with pytest.raises(etree.XMLSyntaxError, match="(?i)amplification"):+ loader_class(str(bomb_path), **loader_kwargs).load()++ with pytest.raises(IsolatedLoaderError) as excinfo:load_from_bytes(payload, ".xml", "bomb.xml")- assert "amplification" in str(excinfo.value).lower()+ assert type(excinfo.value) is IsolatedLoaderError+ assert "refused the document" in str(excinfo.value)assert extract_text_from_bytes(payload, ".xml", "bomb.xml") is Nonedef test_positive_control_ordinary_xml_still_parses(self):diff --git a/tests/research_library/routes/test_rag_routes_upload_main_port.py b/tests/research_library/routes/test_rag_routes_upload_main_port.pyindex 9be052c5c3..90a3247935 100644--- a/tests/research_library/routes/test_rag_routes_upload_main_port.py+++ b/tests/research_library/routes/test_rag_routes_upload_main_port.py@@ -1197,6 +1197,99 @@ class TestUploadToCollection:assert len(rdata["errors"]) == 1assert "Could not extract text" in rdata["errors"][0]["error"]+ def test_upload_busy_parser_is_reported_as_retryable(self):+ """New, not ported: a saturated parser is not an unreadable file.++ When both bounded parser slots are serving other uploads, the file+ gets a retry message instead of "Could not extract text", and the+ rest of the batch still runs with every SAVEPOINT closed.+ """+ from local_deep_research.security.isolated_loader import (+ ParserBusyError,+ )++ mock_coll = Mock()+ mock_coll.id = "coll-1"+ db_session = _make_db_session()+ db_session.query = Mock(+ side_effect=_model_query_side_effect(collection=mock_coll)+ )++ with _upload_env(+ db_session=db_session,+ extra_patches=_extraction_patches(+ extract_side_effect=[+ ParserBusyError("document parser capacity reached"),+ "",+ ]+ ),+ ):+ status, rdata = _body(+ _run_upload(+ [("busy.docx", b"first"), ("empty.docx", b"second")]+ )+ )++ assert status == 200+ assert rdata["summary"]["successful"] == 0+ errors = {e["filename"]: e["error"] for e in rdata["errors"]}+ assert errors["busy.docx"] == (+ "Document parser busy with other uploads; upload this file again"+ )+ assert "Could not extract text" in errors["empty.docx"]+ assert _roles(db_session) == [("read", 1), ("read", 2), ("write", 2)]+ assert not any(sp.is_active for sp in db_session._savepoints)++ def test_upload_missing_nltk_data_says_how_to_install_it(self):+ """New, not ported: missing parser data is not an unreadable file.++ The parser child never downloads NLTK data. When a parse needs data+ the server lacks, the file's error names the install command (and+ nothing from the file), and the rest of the batch still runs with+ every SAVEPOINT closed.+ """+ from local_deep_research.security.isolated_loader import (+ ParserDataMissingError,+ )++ mock_coll = Mock()+ mock_coll.id = "coll-1"+ db_session = _make_db_session()+ db_session.query = Mock(+ side_effect=_model_query_side_effect(collection=mock_coll)+ )++ with _upload_env(+ db_session=db_session,+ extra_patches=_extraction_patches(+ extract_side_effect=[+ ParserDataMissingError(+ "document parser NLTK data is not installed"+ ),+ "",+ ]+ ),+ ):+ status, rdata = _body(+ _run_upload(+ [("nodata.docx", b"first"), ("empty.docx", b"second")]+ )+ )++ assert status == 200+ assert rdata["summary"]["successful"] == 0+ errors = {e["filename"]: e["error"] for e in rdata["errors"]}+ assert errors["nodata.docx"] == (+ "NLTK data needed to parse this file is not installed on the "+ "server; install it with: python -m nltk.downloader punkt_tab "+ "averaged_perceptron_tagger_eng (run it as the user that runs "+ "the server; the official Docker image already includes this "+ "data)"+ )+ assert "Could not extract text" in errors["empty.docx"]+ assert _roles(db_session) == [("read", 1), ("read", 2), ("write", 2)]+ assert not any(sp.is_active for sp in db_session._savepoints)+def test_upload_new_doc_success_text_only(self):"""Ported from ``...::test_upload_new_doc_success_text_only``.diff --git a/tests/security/test_eml_attachments_not_partitioned.py b/tests/security/test_eml_attachments_not_partitioned.pyindex 81a94ba89f..2d12a606c7 100644--- a/tests/security/test_eml_attachments_not_partitioned.py+++ b/tests/security/test_eml_attachments_not_partitioned.py@@ -15,6 +15,7 @@ without the zip-container guard. The registry therefore passesfrom __future__ import annotationsimport io+import jsonimport structfrom email.message import EmailMessagefrom unittest.mock import patch@@ -98,7 +99,7 @@ def test_registry_disables_attachment_processing():@pytest.mark.parametrize("kind", ["rtf", "doc", "docx"])-def test_attachment_converters_and_parsers_never_run(kind):+def test_attachment_converters_and_parsers_never_run(kind, tmp_path):"""Each attachment type reaches its unbounded converter on revert."""pytest.importorskip("unstructured.partition.email")pypandoc = pytest.importorskip("pypandoc")@@ -106,9 +107,7 @@ def test_attachment_converters_and_parsers_never_run(kind):udoc = pytest.importorskip("unstructured.partition.doc")utext = pytest.importorskip("unstructured.partition.text")- from local_deep_research.document_loaders.bytes_loader import (- load_from_bytes,- )+ from local_deep_research.security import isolated_loader, isolated_workerattachments = {"rtf": (b"{\\rtf1\\ansi RTFATTACHMENT}", "rtf", "notes.rtf"),@@ -120,6 +119,8 @@ def test_attachment_converters_and_parsers_never_run(kind):),}payload = _eml(*attachments[kind])+ source = tmp_path / "report.eml"+ source.write_bytes(payload)calls: list[str] = []@@ -131,14 +132,21 @@ def test_attachment_converters_and_parsers_never_run(kind):return _spywith (- # Classification is unrelated to attachment dispatch and would- # otherwise install a spaCy model in the test environment.+ # Classification is unrelated to attachment dispatch. Without this+ # patch it would need NLTK data, which tests get only from the+ # nltk_parser_data fixture; with it, the parse needs none.patch.object(utext, "is_possible_narrative_text", return_value=True),patch.object(pypandoc, "convert_file", _record("convert_file")),patch.object(udoc, "convert_office_doc", _record("convert_office_doc")),patch.object(docx, "Document", _record("docx.Document")),):- docs = load_from_bytes(payload, ".eml", "report.eml")+ # Spies must run inside the parser boundary. The upload routing and+ # normal real-child round trip are covered in test_isolated_text_formats.+ result = isolated_worker._result(str(source), ".eml")+ assert result["status"] == "ok"+ docs = isolated_loader._documents_from_output(+ json.dumps(result).encode(), extension=".eml"+ )assert calls == []text = "\n".join(d.page_content for d in docs)diff --git a/tests/security/test_isolated_text_formats.py b/tests/security/test_isolated_text_formats.pynew file mode 100644index 0000000000..b9acf5bb03--- /dev/null+++ b/tests/security/test_isolated_text_formats.py@@ -0,0 +1,168 @@+"""Shared upload-parser behavior for registered structured text formats."""++import json+from email.message import EmailMessage+from pathlib import Path+from time import strptime, struct_time++import pytest+from langchain_core.documents import Document++from local_deep_research.document_loaders import bytes_loader+from local_deep_research.security import isolated_loader, isolated_worker++TEXT = "Otters build dams near rivers."+ENEX = (+ "<en-export><note><title>Sample note</title>"+ f"<content><![CDATA[<en-note><p>{TEXT}</p></en-note>]]></content>"+ "<created>20240305T134500Z</created><updated/>"+ "</note></en-export>"+).encode()+++def _email() -> bytes:+ message = EmailMessage()+ message["From"] = "[email protected]"+ message["To"] = "[email protected]"+ message["Subject"] = "Sample document"+ message.set_content("Plain message alternative.")+ message.add_alternative(+ f"<html><body><p>{TEXT}</p></body></html>", subtype="html"+ )+ return message.as_bytes()+++SAMPLES = {+ ".md": f"# Sample\n\n{TEXT}\n".encode(),+ ".markdown": f"# Sample\n\n{TEXT}\n".encode(),+ ".eml": _email(),+ ".xml": f"<root><paragraph>{TEXT}</paragraph></root>".encode(),+ ".enex": ENEX,+}++[email protected]("extension", SAMPLES)+def test_structured_text_uploads_use_the_shared_child_path(+ monkeypatch, extension+):+ calls = []+ paths = []++ def isolated(path, ext):+ paths.append(Path(path))+ assert Path(path).read_bytes() == SAMPLES[extension]+ calls.append(ext)+ return [Document(page_content=TEXT)]++ def in_process(*args, **kwargs):+ raise AssertionError("structured text did not use the child path")++ monkeypatch.setattr(bytes_loader, "load_documents_isolated", isolated)+ monkeypatch.setattr(+ bytes_loader,+ "get_loader_class_for_extension",+ lambda ext: (in_process, {}),+ )+ documents = bytes_loader.load_from_bytes(+ SAMPLES[extension], extension, f"sample{extension}"+ )+ assert calls == [extension]+ assert documents[0].metadata["original_filename"] == f"sample{extension}"+ assert paths and all(not path.exists() for path in paths)+++def test_upload_input_is_cleaned_when_staging_write_fails(monkeypatch):+ named_temporary_file = bytes_loader.tempfile.NamedTemporaryFile+ paths = []++ class FailedWrite:+ def __init__(self, *args, **kwargs):+ self.stream = named_temporary_file(*args, **kwargs)+ self.name = self.stream.name+ paths.append(Path(self.name))++ def __enter__(self):+ return self++ def __exit__(self, *args):+ self.stream.close()++ def write(self, data):+ self.stream.write(data[:4])+ raise OSError("temporary input write unavailable")++ monkeypatch.setattr(+ bytes_loader.tempfile, "NamedTemporaryFile", FailedWrite+ )+ with pytest.raises(OSError, match="write unavailable"):+ bytes_loader.load_from_bytes(SAMPLES[".md"], ".md", "sample.md")+ assert paths and all(not path.exists() for path in paths)++[email protected]("extension", SAMPLES)+def test_normal_structured_text_round_trips_through_the_real_child(extension):+ documents = bytes_loader.load_from_bytes(+ SAMPLES[extension], extension, f"sample{extension}"+ )+ assert TEXT in "\n".join(document.page_content for document in documents)+ assert all(+ document.metadata["original_filename"] == f"sample{extension}"+ for document in documents+ )+ if extension == ".enex":+ assert documents[0].metadata["title"] == "Sample note"+ assert documents[0].metadata["created"] == strptime(+ "20240305T134500Z", "%Y%m%dT%H%M%SZ"+ )+ assert isinstance(documents[0].metadata["created"], struct_time)+ assert documents[0].metadata["updated"] is None+++def test_evernote_metadata_keeps_dates_tags_and_optional_values(monkeypatch):+ created = strptime("20240305T134500Z", "%Y%m%dT%H%M%SZ")+ metadata = {"created": created, "updated": None, "tag": ["work", "urgent"]}++ class Loader:+ def __init__(self, path, **kwargs):+ pass++ def load(self):+ return [Document(page_content=TEXT, metadata=metadata)]++ from local_deep_research.document_loaders import loader_registry++ monkeypatch.setattr(+ loader_registry,+ "get_loader_class_for_extension",+ lambda extension: (Loader, {}),+ )+ result = isolated_worker._result("unused", ".enex")+ assert result["status"] == "ok"+ encoded = json.dumps(result).encode()+ restored = isolated_loader._documents_from_output(+ encoded, extension=".enex"+ )+ assert restored[0].metadata == metadata+ with pytest.raises(+ isolated_loader.IsolatedLoaderError, match="invalid documents"+ ):+ isolated_loader._documents_from_output(encoded, extension=".docx")+++ "value",+ [[1] * 8, [True] * 9, {"unexpected": "object"}, [["nested"]]],+)+def test_evernote_protocol_refuses_unsupported_date_values(value):+ encoded = json.dumps(+ {+ "status": "ok",+ "documents": [+ {"page_content": TEXT, "metadata": {"created": value}}+ ],+ }+ ).encode()+ with pytest.raises(+ isolated_loader.IsolatedLoaderError, match="invalid documents"+ ):+ isolated_loader._documents_from_output(encoded, extension=".enex")diff --git a/tests/security/test_isolated_upload_loader.py b/tests/security/test_isolated_upload_loader.pynew file mode 100644index 0000000000..eb898e7b87--- /dev/null+++ b/tests/security/test_isolated_upload_loader.py@@ -0,0 +1,1385 @@+"""Resource-boundary regressions for uploaded document parsing."""++import io+import json+import os+import signal+import subprocess+import sys+import threading+import time+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++import pytest+from langchain_core.documents import Document++from local_deep_research.document_loaders import bytes_loader+from local_deep_research.security import isolated_loader, isolated_worker+++def test_child_with_no_output_is_killed_at_deadline():+ started = time.monotonic()+ with pytest.raises(isolated_loader.IsolatedLoaderError, match="timed out"):+ isolated_loader._run_capped(+ [sys.executable, "-c", "import time; time.sleep(30)"], 0.1+ )+ assert time.monotonic() - started < 5+++def test_spawn_failure_does_not_fall_back_to_unbounded_parse(monkeypatch):+ def unavailable(*args, **kwargs):+ raise OSError("process creation unavailable")++ monkeypatch.setattr(isolated_loader.subprocess, "Popen", unavailable)+ with pytest.raises(+ isolated_loader.IsolatedLoaderError, match="could not start"+ ):+ isolated_loader._run_capped([sys.executable, "-c", "pass"], 1)+++def test_invalid_process_configuration_is_a_parser_failure(monkeypatch):+ def unavailable(*args, **kwargs):+ raise ValueError("invalid process configuration")++ monkeypatch.setattr(isolated_loader.subprocess, "Popen", unavailable)+ with pytest.raises(+ isolated_loader.IsolatedLoaderError, match="could not start"+ ):+ isolated_loader._run_capped([sys.executable, "-c", "pass"], 1)+++def test_parent_rejects_unbounded_child_output(monkeypatch):+ monkeypatch.setattr(isolated_loader, "MAX_PROTOCOL_BYTES", 1_024)+ with pytest.raises(+ isolated_loader.IsolatedLoaderError, match="output exceeded"+ ):+ isolated_loader._run_capped(+ [sys.executable, "-c", "import os; os.write(1, b'A' * 2048)"], 5+ )+++def test_timeout_returns_while_another_writer_keeps_pipe_open(monkeypatch):+ # Simulate an inherited writer that outlives the parser. The test owns+ # that writer and closes it in finally, so even the broken implementation+ # is cleaned up. No detached process is needed.+ read_fd, write_fd = os.pipe()+ popen = subprocess.Popen+ children = []++ def shared_pipe(*args, **kwargs):+ kwargs["stdout"] = write_fd+ child = popen(*args, **kwargs)+ child.stdout = os.fdopen(+ read_fd, "rb", buffering=kwargs.get("bufsize", -1)+ )+ children.append(child)+ return child++ monkeypatch.setattr(isolated_loader.subprocess, "Popen", shared_pipe)+ with ThreadPoolExecutor(max_workers=1) as executor:+ future = executor.submit(+ isolated_loader._run_capped,+ [sys.executable, "-c", "pass"],+ 0.1,+ )+ try:+ with pytest.raises(+ isolated_loader.IsolatedLoaderError, match="timed out"+ ):+ # Cleanup must finish before the test releases the remaining+ # writer, not wait for EOF while closing a buffered reader.+ future.result(timeout=5)+ finally:+ os.close(write_fd)+ if not children:+ os.close(read_fd)++ assert len(children) == 1+ assert children[0].poll() is not None+ assert children[0].stdout.closed+++def test_small_over_limit_output_is_refused_before_eof(monkeypatch):+ monkeypatch.setattr(isolated_loader, "MAX_PROTOCOL_BYTES", 1_024)+ # More than the output limit, less than one buffered read. The child+ # keeps its pipe open, as a parser waiting during shutdown might do.+ with pytest.raises(+ isolated_loader.IsolatedLoaderError, match="output exceeded"+ ):+ isolated_loader._run_capped(+ [+ sys.executable,+ "-c",+ "import os, time; os.write(1, b'A' * 2048); time.sleep(30)",+ ],+ 2,+ )+++def test_nonblocking_setup_failure_kills_and_closes_child(monkeypatch):+ popen = subprocess.Popen+ children = []++ def record_child(*args, **kwargs):+ child = popen(*args, **kwargs)+ children.append(child)+ return child++ def unavailable(*args):+ raise OSError("nonblocking pipes unavailable")++ monkeypatch.setattr(isolated_loader.subprocess, "Popen", record_child)+ monkeypatch.setattr(isolated_loader.os, "set_blocking", unavailable)+ with pytest.raises(+ isolated_loader.IsolatedLoaderError, match="pipe.*configured"+ ):+ isolated_loader._run_capped(+ [sys.executable, "-c", "import time; time.sleep(30)"], 1+ )+ assert len(children) == 1+ assert children[0].poll() is not None+ assert children[0].stdout.closed+++def test_exact_output_limit_is_returned_whole(monkeypatch):+ monkeypatch.setattr(isolated_loader, "MAX_PROTOCOL_BYTES", 100_000)+ expected = b"a" * 50_000 + b"b" * 50_000+ output = isolated_loader._run_capped(+ [+ sys.executable,+ "-c",+ "import sys; "+ "sys.stdout.buffer.write(b'a' * 50000); "+ "sys.stdout.buffer.flush(); "+ "sys.stdout.buffer.write(b'b' * 50000)",+ ],+ 5,+ )+ assert output == expected+++def test_parser_capacity_rejects_burst_before_spawn(monkeypatch):+ slots = threading.BoundedSemaphore(1)+ slots.acquire()+ monkeypatch.setattr(isolated_loader, "_parser_slots", slots)++ def forbidden(*args, **kwargs):+ raise AssertionError("saturated parser launched a child")++ monkeypatch.setattr(isolated_loader, "_run_capped", forbidden)+ with pytest.raises(isolated_loader.IsolatedLoaderError, match="capacity"):+ isolated_loader.load_documents_isolated("unused", ".docx")+++def test_parser_capacity_is_held_until_result_validation_finishes(monkeypatch):+ slots = threading.BoundedSemaphore(1)+ monkeypatch.setattr(isolated_loader, "_parser_slots", slots)+ output = (+ b'{"status":"ok","documents":[{"page_content":"text","metadata":{}}]}'+ )+ monkeypatch.setattr(isolated_loader, "_run_capped", lambda *args: output)+ entered = threading.Event()+ release = threading.Event()+ main_thread = threading.current_thread()+ loads = json.loads++ def held_decode(data, *args, **kwargs):+ if data == output and threading.current_thread() is not main_thread:+ entered.set()+ assert release.wait(5), "test did not release result validation"+ return loads(data, *args, **kwargs)++ monkeypatch.setattr(isolated_loader.json, "loads", held_decode)+ with ThreadPoolExecutor(max_workers=1) as executor:+ future = executor.submit(+ isolated_loader.load_documents_isolated, "unused", ".docx"+ )+ try:+ assert entered.wait(5), "result validation did not start"+ with pytest.raises(+ isolated_loader.IsolatedLoaderError, match="capacity"+ ):+ isolated_loader.load_documents_isolated("unused", ".docx")+ finally:+ release.set()+ assert future.result(timeout=5)[0].page_content == "text"++ # The completed parse returns its slot for the next caller.+ assert (+ isolated_loader.load_documents_isolated("unused", ".docx")[+ 0+ ].page_content+ == "text"+ )+++ "invalid_output",+ [b"not JSON", b'{"status":"ok","documents":[{"page_content":42}]}'],+)+def test_invalid_result_releases_parser_capacity(monkeypatch, invalid_output):+ monkeypatch.setattr(+ isolated_loader, "_parser_slots", threading.BoundedSemaphore(1)+ )+ outputs = iter([invalid_output, b'{"status":"ok","documents":[]}'])+ monkeypatch.setattr(+ isolated_loader, "_run_capped", lambda *args: next(outputs)+ )++ with pytest.raises(isolated_loader.IsolatedLoaderError, match="invalid"):+ isolated_loader.load_documents_isolated("unused", ".docx")+ assert isolated_loader.load_documents_isolated("unused", ".docx") == []++[email protected](sys.platform != "linux", reason="Linux RLIMIT_DATA only")+def test_worker_data_limit_refuses_new_allocation():+ script = """+from pathlib import Path+from local_deep_research.security.isolated_worker import _cap_data_memory+status = Path('/proc/self/status').read_text()+current = int(next(line.split()[1] for line in status.splitlines()+ if line.startswith('VmData:'))) * 1024+_cap_data_memory(current + 32 * 1024 * 1024)+try:+ data = bytearray(128 * 1024 * 1024)+except MemoryError:+ print('bounded')+else:+ raise SystemExit('allocation escaped data limit')+"""+ result = subprocess.run(+ [sys.executable, "-c", script],+ check=False,+ capture_output=True,+ text=True,+ timeout=10,+ )+ assert result.returncode == 0, result.stderr+ assert result.stdout.strip() == "bounded"+++def test_worker_refuses_too_many_documents_before_writing(monkeypatch):+ class Loader:+ def __init__(self, path, **kwargs):+ self.path = path++ def load(self):+ return [Document(page_content="text") for _ in range(3)]++ from local_deep_research.document_loaders import loader_registry++ monkeypatch.setattr(isolated_loader, "MAX_DOCUMENTS", 2)+ monkeypatch.setattr(+ loader_registry,+ "get_loader_class_for_extension",+ lambda extension: (Loader, {}),+ )+ assert isolated_worker._result("unused", ".docx") == {+ "status": "error",+ "kind": "limit",+ }+++def test_worker_counts_metadata_in_its_output_budget(monkeypatch):+ class Loader:+ def __init__(self, path, **kwargs):+ pass++ def load(self):+ return [+ Document(page_content="small", metadata={"blob": "A" * 2_000})+ ]++ from local_deep_research.document_loaders import loader_registry++ monkeypatch.setattr(isolated_loader, "MAX_PROTOCOL_BYTES", 1_024)+ monkeypatch.setattr(+ loader_registry,+ "get_loader_class_for_extension",+ lambda extension: (Loader, {}),+ )+ assert isolated_worker._result("unused", ".docx") == {+ "status": "error",+ "kind": "limit",+ }+++def test_xlsx_worker_reapplies_drawing_guard_before_loader(monkeypatch):+ from local_deep_research.document_loaders import (+ loader_registry,+ openpyxl_hardening,+ )++ monkeypatch.setattr(+ openpyxl_hardening, "disable_openpyxl_drawing_reads", lambda: False+ )++ def forbidden(extension):+ raise AssertionError("spreadsheet loader ran without drawing guard")++ monkeypatch.setattr(+ loader_registry, "get_loader_class_for_extension", forbidden+ )+ assert isolated_worker._result("unused", ".xlsx") == {+ "status": "error",+ "kind": "guard",+ }+++def test_in_process_text_upload_has_no_child_text_limit():+ # The character limit belongs to the bounded child parse. Plain text,+ # CSV and the other formats parsed in this process are joined whole,+ # as before the child existed: CSV rows become "header: value" lines,+ # so a CSV upload of a few MB can pass this many characters.+ text = "a" * (isolated_loader.MAX_TEXT_CHARS + 1)+ extracted = bytes_loader.extract_text_from_bytes(+ text.encode(), ".txt", "large.txt"+ )+ assert extracted is not None+ assert len(extracted) == len(text)+ assert extracted == text+++def test_legacy_conversion_and_zip_guard_precede_isolated_loader(monkeypatch):+ events: list[object] = []+ monkeypatch.setattr(+ bytes_loader, "is_extension_supported", lambda ext: True+ )+ monkeypatch.setattr(+ bytes_loader,+ "convert_legacy_office_bytes",+ lambda content, ext: events.append(("convert", ext)) or b"converted",+ )+ monkeypatch.setattr(+ bytes_loader,+ "validate_zip_container",+ lambda content, ext: events.append(("guard", content, ext)),+ )+ monkeypatch.setattr(+ bytes_loader,+ "get_loader_class_for_extension",+ lambda ext: (object, {}),+ )++ def isolated(path, ext):+ assert Path(path).read_bytes() == b"converted"+ events.append(("isolated", ext))+ return [Document(page_content="safe", metadata={})]++ monkeypatch.setattr(bytes_loader, "load_documents_isolated", isolated)+ documents = bytes_loader.load_from_bytes(b"ole", ".doc", "sample.doc")+ assert documents[0].page_content == "safe"+ assert events == [+ ("convert", ".doc"),+ ("guard", b"converted", ".docx"),+ ("isolated", ".docx"),+ ]+++# Real-worker and limit pins. Each limit below is enforced on both sides of+# the pipe or in the real child, so a test that patched the child out could+# not notice either half going missing.++DOCX_TEXT = "Bounded parser round trip."+MHTML = (+ b"MIME-Version: 1.0\r\nContent-Type: text/html\r\n\r\n"+ b"<html><body><p>hello mhtml</p></body></html>\r\n"+)+++def _docx_bytes() -> bytes:+ docx = pytest.importorskip("docx")+ document = docx.Document()+ document.add_paragraph(DOCX_TEXT)+ buffer = io.BytesIO()+ document.save(buffer)+ return buffer.getvalue()+++def _worker_output(*texts: str) -> bytes:+ return json.dumps(+ {+ "status": "ok",+ "documents": [+ {"page_content": text, "metadata": {}} for text in texts+ ],+ }+ ).encode()+++def _stub_registry(monkeypatch, loader_class):+ from local_deep_research.document_loaders import loader_registry++ monkeypatch.setattr(+ loader_registry,+ "get_loader_class_for_extension",+ lambda extension: (loader_class, {}),+ )+++def _worker_argv(path: str, *, cpu_seconds: int | None = None) -> str:+ # A script line giving the worker the argv load_documents_isolated+ # passes. Each script runs as a direct child of this test process, so+ # this process's ID is its parent's.+ if cpu_seconds is None:+ cpu_seconds = isolated_loader.CHILD_CPU_SECONDS+ return (+ f"sys.argv = ['worker', {path!r}, '.docx', "+ f"{str(isolated_loader.MAX_CHILD_DATA_BYTES)!r}, "+ f"{str(cpu_seconds)!r}, {str(os.getpid())!r}]"+ )+++def test_real_docx_round_trips_through_the_real_worker():+ # Nothing is patched: the ZIP guard, the routing decision, the real child+ # and its registry loader, the pipe protocol and parent validation.+ documents = bytes_loader.load_from_bytes(+ _docx_bytes(), ".docx", "round-trip.docx"+ )+ assert [doc.page_content for doc in documents] == [DOCX_TEXT]+ assert documents[0].metadata["original_filename"] == "round-trip.docx"+++def test_real_worker_parses_without_importing_the_ml_stack(tmp_path):+ # langchain_text_splitters imports sentence-transformers, transformers+ # and torch. The worker never splits text, so no parse should pay for+ # them in time or memory.+ source = tmp_path / "plain.docx"+ source.write_bytes(_docx_bytes())+ report = tmp_path / "loaded.json"+ script = "\n".join(+ [+ "import json, sys",+ "from local_deep_research.security import isolated_worker",+ _worker_argv(str(source)),+ "code = isolated_worker.main()",+ "names = ('torch', 'transformers', 'sentence_transformers')",+ "loaded = [n for n in names if sys.modules.get(n) is not None]",+ f"with open({str(report)!r}, 'w') as handle:",+ " handle.write(json.dumps(loaded))",+ "raise SystemExit(code)",+ ]+ )+ result = subprocess.run(+ [sys.executable, "-c", script],+ check=False,+ capture_output=True,+ timeout=150,+ )+ assert result.returncode == 0, result.stderr[-2000:]+ payload = json.loads(result.stdout)+ assert payload["status"] == "ok", payload+ assert [r["page_content"] for r in payload["documents"]] == [DOCX_TEXT]+ assert json.loads(report.read_text()) == []++[email protected](sys.platform != "linux", reason="Linux RLIMIT_DATA only")+def test_real_worker_has_live_data_limit(monkeypatch, tmp_path):+ # The unit test above calls _cap_data_memory itself. This one uses the+ # production argv and main(): a cap far below what the parser libraries+ # need to import must make the real child refuse a valid document.+ source = tmp_path / "capped.docx"+ source.write_bytes(_docx_bytes())+ monkeypatch.setattr(+ isolated_loader, "MAX_CHILD_DATA_BYTES", 64 * 1024 * 1024+ )+ # A native import may report a failed mapping rather than MemoryError.+ # A timeout, crash or ordinary parser error must still fail this check.+ with pytest.raises(+ (+ isolated_loader.ParserMemoryLimitError,+ isolated_loader.ParserResourceError,+ )+ ):+ isolated_loader.load_documents_isolated(str(source), ".docx")+++def test_worker_reports_memory_exhaustion_as_its_own_kind(tmp_path):+ # A MemoryError from the loader is the data limit, not an unreadable+ # document ("parser") or another limit ("limit"), and main() reports it+ # with a result encoded before the limit applied.+ script = "\n".join(+ [+ "import os, sys",+ "from local_deep_research.security import isolated_worker",+ "def parse(path, extension):",+ " raise MemoryError",+ "isolated_worker._result = parse",+ _worker_argv("unused"),+ "raise SystemExit(isolated_worker.main())",+ ]+ )+ result = subprocess.run(+ [sys.executable, "-c", script],+ check=False,+ capture_output=True,+ timeout=60,+ )+ assert result.returncode == 0, result.stderr[-2000:]+ assert json.loads(result.stdout) == {"status": "error", "kind": "memory"}+ with pytest.raises(isolated_loader.ParserMemoryLimitError):+ isolated_loader._documents_from_output(result.stdout)+++def test_worker_lets_a_loader_memory_error_reach_main(monkeypatch):+ class Loader:+ def __init__(self, path, **kwargs):+ pass++ def load(self):+ raise MemoryError++ _stub_registry(monkeypatch, Loader)+ with pytest.raises(MemoryError):+ isolated_worker._result("unused", ".docx")+++ "output",+ [+ b"[" * 200_000 + b"]" * 200_000,+ (+ b'{"status":"ok","documents":[{"page_content":"x","metadata":'+ b'{"deep":' + b"[" * 200_000 + b"]" * 200_000 + b"}}]}"+ ),+ ],+ ids=["top-level", "inside-metadata"],+)+def test_parent_refuses_deeply_nested_output(output):+ # The structure scan refuses these before json.loads would recurse;+ # the depth-only and RecursionError cases are pinned separately below.+ assert len(output) < isolated_loader.MAX_PROTOCOL_BYTES+ with pytest.raises(isolated_loader.IsolatedLoaderError, match="invalid"):+ isolated_loader._documents_from_output(output)+++def test_result_depth_is_bounded_before_json_decode(monkeypatch):+ # One level past the depth limit, and far under the collection and+ # token caps, so only the depth check can refuse it.+ depth = isolated_loader._MAX_JSON_DEPTH + 1+ output = b"[" * depth + b"]" * depth+ assert depth < 2 + 2 * isolated_loader.MAX_DOCUMENTS++ def unexpected_decode(*args, **kwargs):+ raise AssertionError("over-deep structure reached JSON decoding")++ monkeypatch.setattr(isolated_loader.json, "loads", unexpected_decode)+ with pytest.raises(+ isolated_loader.IsolatedLoaderError, match="invalid documents"+ ):+ isolated_loader._documents_from_output(output)+++def test_json_recursion_error_is_a_parser_failure(monkeypatch):+ # The depth scan normally stops nesting long before the decoder's own+ # limit, so reach the RecursionError branch directly.+ def too_deep(*args, **kwargs):+ raise RecursionError("maximum recursion depth exceeded")++ monkeypatch.setattr(isolated_loader.json, "loads", too_deep)+ with pytest.raises(+ isolated_loader.IsolatedLoaderError, match="invalid output"+ ) as excinfo:+ isolated_loader._documents_from_output(b'{"status":"ok"}')+ assert isinstance(excinfo.value.__cause__, RecursionError)+++ "output",+ [+ b"[[],[],[],[],[],[],[],[]]",+ b'{"a":0,"b":0,"c":0,"d":0,"e":0,"f":0,"g":0,"h":0}',+ ],+ ids=["collections", "fields"],+)+def test_result_structure_is_bounded_before_json_decode(monkeypatch, output):+ monkeypatch.setattr(isolated_loader, "MAX_DOCUMENTS", 1)+ monkeypatch.setattr(isolated_loader, "MAX_METADATA_FIELDS", 0)++ def unexpected_decode(*args, **kwargs):+ raise AssertionError("over-limit structure reached JSON decoding")++ monkeypatch.setattr(isolated_loader.json, "loads", unexpected_decode)+ with pytest.raises(isolated_loader.IsolatedLoaderError, match="invalid"):+ isolated_loader._documents_from_output(output)+++def test_result_scan_respects_quoted_and_escaped_syntax():+ # An odd number of escaped quotes ends the string early for a scan+ # that ignores backslashes, exposing "]}" as structure. A string ending+ # in an escaped backslash keeps a scan that treats every quote after a+ # backslash as escaped inside the string, so later quoted brackets+ # flip to structure. Either mistake refuses this valid output.+ texts = [+ 'Quoted "text", backslash \\ and braces [{]}:,',+ 'one quote " then ]}',+ "ends in a backslash \\",+ "[{]}",+ ]+ documents = isolated_loader._documents_from_output(_worker_output(*texts))+ assert [document.page_content for document in documents] == texts++[email protected]("encoding", ["utf-16-le", "utf-32-le"])+def test_result_requires_the_workers_utf8_encoding(encoding):+ output = '{"status":"ok","documents":[]}'.encode(encoding)+ with pytest.raises(isolated_loader.IsolatedLoaderError, match="invalid"):+ isolated_loader._documents_from_output(output)+++def test_json_value_error_is_a_parser_failure(monkeypatch):+ def invalid_integer(*args, **kwargs):+ raise ValueError("integer conversion limit")++ monkeypatch.setattr(isolated_loader.json, "loads", invalid_integer)+ with pytest.raises(isolated_loader.IsolatedLoaderError, match="invalid"):+ isolated_loader._documents_from_output(b'{"status":"ok"}')+++def test_metadata_field_budget_is_cumulative_in_parent_and_worker(monkeypatch):+ monkeypatch.setattr(isolated_loader, "MAX_METADATA_FIELDS", 2)+ records = [+ Document(page_content="a", metadata={"first": "1"}),+ Document(page_content="b", metadata={"second": "2"}),+ ]++ class Loader:+ def __init__(self, path, **kwargs):+ pass++ def load(self):+ return records++ _stub_registry(monkeypatch, Loader)+ result = isolated_worker._result("unused", ".docx")+ assert result["status"] == "ok"+ assert (+ len(isolated_loader._documents_from_output(json.dumps(result).encode()))+ == 2+ )+ records.append(Document(page_content="c", metadata={"third": "3"}))+ with pytest.raises(isolated_loader.IsolatedLoaderError, match="exceeded"):+ isolated_loader._documents_from_output(+ json.dumps(+ {+ "status": "ok",+ "documents": [record.model_dump() for record in records],+ }+ ).encode()+ )+ assert isolated_worker._result("unused", ".docx") == {+ "status": "error",+ "kind": "limit",+ }+++ ("message", "kind", "exception"),+ [+ ("No module named docx", "ImportError", ImportError),+ (+ "library: cannot allocate memory",+ "memory",+ isolated_loader.ParserMemoryLimitError,+ ),+ (+ "library: failed to map segment from shared object",+ "resource",+ isolated_loader.ParserResourceError,+ ),+ ],+)+def test_worker_distinguishes_dependency_and_mapping_failures(+ monkeypatch, message, kind, exception+):+ class Loader:+ def __init__(self, path, **kwargs):+ pass++ def load(self):+ raise ImportError(message)++ _stub_registry(monkeypatch, Loader)+ result = isolated_worker._result("unused", ".docx")+ assert result == {"status": "error", "kind": kind}+ with pytest.raises(exception):+ isolated_loader._documents_from_output(json.dumps(result).encode())+++ "value",+ [1, 1.5, None, True, ["a"], {"a": "b"}],+ ids=["int", "float", "null", "bool", "list", "object"],+)+def test_parent_refuses_non_string_metadata_values(value):+ def output(metadata_value):+ return json.dumps(+ {+ "status": "ok",+ "documents": [+ {"page_content": "x", "metadata": {"k": metadata_value}}+ ],+ }+ ).encode()++ documents = isolated_loader._documents_from_output(output("string"))+ assert documents[0].metadata == {"k": "string"}+ with pytest.raises(+ isolated_loader.IsolatedLoaderError, match="invalid documents"+ ):+ isolated_loader._documents_from_output(output(value))+++def test_documented_limits_match_the_code():+ # docs/library-and-rag.md and the changelog state these numbers; a+ # change to either side must change the other.+ assert isolated_loader.PARSE_TIMEOUT_SECONDS == 90+ assert isolated_loader.MAX_TEXT_CHARS == 10_000_000+ assert isolated_loader.MAX_PROTOCOL_BYTES == 40_000_000 # 40 MB+ assert isolated_loader.MAX_DOCUMENTS == 10_000+ assert isolated_loader.MAX_CHILD_DATA_BYTES == 3 * 1024**3 # 3 GiB+ assert isolated_loader.CHILD_CPU_SECONDS == 120+ assert isolated_loader.MAX_CONCURRENT_PARSERS == 2+ root = Path(__file__).resolve().parents[2]+ for doc in (+ root / "docs" / "library-and-rag.md",+ root / "changelog.d" / "7147.security.md",+ ):+ text = " ".join(doc.read_text().split())+ for claim in (+ "90-second deadline",+ "10-million-character text limit",+ "10,000-document limit",+ "40 MB",+ "soft 3 GiB data-memory limit",+ "120",+ ):+ assert claim in text, f"{doc.name} no longer says {claim!r}"+++def test_parent_refuses_cumulative_text_over_limit(monkeypatch):+ monkeypatch.setattr(isolated_loader, "MAX_TEXT_CHARS", 10)+ # The limit counts text across documents as they are joined, and+ # exactly the limit passes: "abcd\n\nefgh" is ten characters.+ documents = isolated_loader._documents_from_output(+ _worker_output("abcd", "efgh")+ )+ assert [doc.page_content for doc in documents] == ["abcd", "efgh"]+ with pytest.raises(+ isolated_loader.IsolatedLoaderError, match="output exceeded"+ ):+ isolated_loader._documents_from_output(_worker_output("abcd", "efghi"))+++def test_parent_counts_join_separators_against_the_text_limit(monkeypatch):+ # extract_text_from_bytes no longer caps its join, so the child's limit+ # must include the separators: "abcd\n\nef" is eight characters, and an+ # empty part adds none.+ monkeypatch.setattr(isolated_loader, "MAX_TEXT_CHARS", 8)+ documents = isolated_loader._documents_from_output(+ _worker_output("abcd", "", "ef")+ )+ assert [doc.page_content for doc in documents] == ["abcd", "", "ef"]+ with pytest.raises(+ isolated_loader.IsolatedLoaderError, match="output exceeded"+ ):+ isolated_loader._documents_from_output(_worker_output("abcd", "efg"))+++def test_oversized_bounded_parse_is_still_refused(monkeypatch):+ # Real limits, through the upload entry point. Two halves whose join is+ # two characters over the limit are refused; at exactly the limit the+ # joined text is returned.+ half = isolated_loader.MAX_TEXT_CHARS // 2+ outputs = iter(+ [+ _worker_output("a" * half, "b" * half),+ _worker_output("a" * half, "b" * (half - 2)),+ ]+ )+ monkeypatch.setattr(+ isolated_loader, "_run_capped", lambda *args: next(outputs)+ )+ over = bytes_loader.extract_text_from_bytes(+ _docx_bytes(), ".docx", "over.docx"+ )+ assert over is None+ exact = bytes_loader.extract_text_from_bytes(+ _docx_bytes(), ".docx", "exact.docx"+ )+ assert exact is not None+ assert len(exact) == isolated_loader.MAX_TEXT_CHARS+++def test_parent_refuses_more_than_max_documents(monkeypatch):+ monkeypatch.setattr(isolated_loader, "MAX_DOCUMENTS", 2)+ output = _worker_output("a", "b")+ assert len(isolated_loader._documents_from_output(output)) == 2+ with pytest.raises(+ isolated_loader.IsolatedLoaderError, match="invalid documents"+ ):+ isolated_loader._documents_from_output(_worker_output("a", "b", "c"))+++def test_worker_dependency_error_maps_to_importerror_at_the_parent(+ monkeypatch,+):+ class Loader:+ def __init__(self, path, **kwargs):+ pass++ def load(self):+ raise ModuleNotFoundError("No module named 'docx'")++ _stub_registry(monkeypatch, Loader)+ result = isolated_worker._result("unused", ".docx")+ assert result == {"status": "error", "kind": "ImportError"}+ # load_from_bytes logs an ImportError as a missing parser dependency,+ # not as a document the parser refused.+ with pytest.raises(ImportError, match="dependency unavailable"):+ isolated_loader._documents_from_output(json.dumps(result).encode())+++def test_worker_refuses_text_over_its_limit(monkeypatch):+ # The worker counts the joined text as the parent does: "abcd\n\nef" is+ # exactly the limit, the empty part adds no separator, and one more+ # character is over it.+ texts = ["abcd", "", "ef"]++ class Loader:+ def __init__(self, path, **kwargs):+ pass++ def load(self):+ return [Document(page_content=text) for text in texts]++ _stub_registry(monkeypatch, Loader)+ monkeypatch.setattr(isolated_loader, "MAX_TEXT_CHARS", 8)+ assert isolated_worker._result("unused", ".docx")["status"] == "ok"+ texts[-1] = "efg"+ assert isolated_worker._result("unused", ".docx") == {+ "status": "error",+ "kind": "limit",+ }+++def test_worker_protocol_survives_native_stdout_writes():+ # Native parser code can write straight to fd 1. Only the JSON result+ # may reach the protocol pipe.+ script = "\n".join(+ [+ "import os, sys",+ "from local_deep_research.security import isolated_worker",+ "def noisy(path, extension):",+ " print('python stdout noise', flush=True)",+ " os.write(1, b'native stdout noise')",+ " return {'status': 'ok', 'documents': []}",+ "isolated_worker._result = noisy",+ _worker_argv("unused"),+ "raise SystemExit(isolated_worker.main())",+ ]+ )+ result = subprocess.run(+ [sys.executable, "-c", script],+ check=False,+ capture_output=True,+ timeout=60,+ )+ assert result.returncode == 0, result.stderr[-2000:]+ assert json.loads(result.stdout) == {"status": "ok", "documents": []}+++def _marked_process_alive(pid: int, marker: bytes) -> bool:+ """Whether ``pid`` is still the marked helper and not yet a zombie."""+ proc = Path(f"/proc/{pid}")+ try:+ if marker not in (proc / "cmdline").read_bytes():+ return False+ state = (proc / "stat").read_text().rsplit(")", 1)[1].split()[0]+ except OSError:+ return False+ return state not in {"Z", "X"}+++ sys.platform != "linux", reason="reads /proc for the helper's state"+)+def test_timeout_kills_the_parsers_descendants(tmp_path):+ # Parsers can start converter or OCR helpers. A timeout must stop the+ # child's whole process group, not only the child.+ pid_file = tmp_path / "helper.pid"+ marker = "time.sleep(61)"+ script = "\n".join(+ [+ "import subprocess, sys, time",+ "helper = subprocess.Popen("+ f"[sys.executable, '-c', 'import time; {marker}'])",+ f"with open({str(pid_file)!r}, 'w') as handle:",+ " handle.write(str(helper.pid))",+ "time.sleep(60)",+ ]+ )+ with pytest.raises(isolated_loader.IsolatedLoaderError, match="timed out"):+ isolated_loader._run_capped([sys.executable, "-c", script], 3)+ pid = int(pid_file.read_text())+ try:+ deadline = time.monotonic() + 5+ while (+ _marked_process_alive(pid, marker.encode())+ and time.monotonic() < deadline+ ):+ time.sleep(0.05)+ assert not _marked_process_alive(pid, marker.encode())+ finally:+ if _marked_process_alive(pid, marker.encode()):+ os.kill(pid, signal.SIGKILL)+++def test_parser_child_gets_its_limits_and_this_process_id(monkeypatch):+ # The child cannot rely on its parent's deadline if the parent dies, so+ # the parent passes the child's own CPU-time limit, a little above that+ # deadline, and its process ID, which the child checks.+ commands = []++ def record(command, timeout_s):+ commands.append(command)+ return _worker_output()++ monkeypatch.setattr(isolated_loader, "_run_capped", record)+ isolated_loader.load_documents_isolated("unused", ".docx")+ (command,) = commands+ assert command[command.index("-m") + 2 :] == [+ "unused",+ ".docx",+ str(isolated_loader.MAX_CHILD_DATA_BYTES),+ str(isolated_loader.CHILD_CPU_SECONDS),+ str(os.getpid()),+ ]+ assert (+ isolated_loader.PARSE_TIMEOUT_SECONDS+ < isolated_loader.CHILD_CPU_SECONDS+ <= 2 * isolated_loader.PARSE_TIMEOUT_SECONDS+ )++[email protected](os.name != "posix", reason="RLIMIT_CPU is POSIX-only")+def test_parser_child_ends_a_parse_past_its_cpu_time_limit():+ # The real main() applies the CPU-time limit from its argv before the+ # parse runs. A parse that keeps a CPU busy past it gets SIGXCPU, with+ # no parent needed to stop it. One second keeps the test short.+ script = "\n".join(+ [+ "import sys",+ "from local_deep_research.security import isolated_worker",+ "def spin(path, extension):",+ " while True:",+ " pass",+ "isolated_worker._result = spin",+ _worker_argv("unused", cpu_seconds=1),+ "raise SystemExit(isolated_worker.main())",+ ]+ )+ result = subprocess.run(+ [sys.executable, "-c", script],+ check=False,+ capture_output=True,+ timeout=60,+ )+ assert result.returncode == -signal.SIGXCPU, result.stderr[-2000:]+++ sys.platform != "linux", reason="PR_SET_PDEATHSIG and /proc are Linux-only"+)+def test_parser_child_is_killed_when_its_parent_dies(tmp_path):+ # A server that crashed or was killed no longer stops its parses at the+ # deadline, and after a restart its parser slots do not count them. A+ # stand-in parent starts the real worker main() the way the server does,+ # passing its own process ID, and is then killed mid-parse.+ pid_file = tmp_path / "worker.pid"+ marker = "parse that outlives its parent"+ worker = "\n".join(+ [+ "import os, sys, time",+ "from local_deep_research.security import isolated_worker",+ "def parse(path, extension):",+ f" with open({str(pid_file)!r} + '.tmp', 'w') as handle:",+ " handle.write(str(os.getpid()))",+ f" os.replace({str(pid_file)!r} + '.tmp', {str(pid_file)!r})",+ " time.sleep(60)",+ " return {'status': 'ok', 'documents': []}",+ "isolated_worker._result = parse",+ f"sys.argv = ['worker', {marker!r}, '.docx', "+ f"{str(isolated_loader.MAX_CHILD_DATA_BYTES)!r}, "+ f"{str(isolated_loader.CHILD_CPU_SECONDS)!r}, sys.argv[1]]",+ "raise SystemExit(isolated_worker.main())",+ ]+ )+ parent = subprocess.Popen(+ [+ sys.executable,+ "-c",+ "import os, subprocess, sys, time\n"+ "subprocess.Popen("+ f"[sys.executable, '-c', {worker!r}, str(os.getpid())])\n"+ "time.sleep(60)\n",+ ]+ )+ pid = None+ try:+ deadline = time.monotonic() + 30+ while not pid_file.exists() and time.monotonic() < deadline:+ time.sleep(0.05)+ assert pid_file.exists(), "the worker never started its parse"+ pid = int(pid_file.read_text())+ assert _marked_process_alive(pid, marker.encode())+ parent.kill()+ parent.wait(timeout=5)+ deadline = time.monotonic() + 5+ while (+ _marked_process_alive(pid, marker.encode())+ and time.monotonic() < deadline+ ):+ time.sleep(0.05)+ assert not _marked_process_alive(pid, marker.encode())+ finally:+ if parent.poll() is None:+ parent.kill()+ parent.wait(timeout=5)+ if pid is not None and _marked_process_alive(pid, marker.encode()):+ os.kill(pid, signal.SIGKILL)+++ sys.platform != "linux", reason="the check accompanies PR_SET_PDEATHSIG"+)+def test_parser_child_does_not_parse_once_its_parent_has_exited(tmp_path):+ # A parent that exits before the child asks for the parent-death signal+ # never triggers it; the child then has another parent. It must refuse+ # instead of parsing for a server that is gone. Here the ID it is given+ # is its own, which is never its parent's.+ parsed = tmp_path / "parsed"+ script = "\n".join(+ [+ "import os, sys",+ "from local_deep_research.security import isolated_worker",+ "def parse(path, extension):",+ f" open({str(parsed)!r}, 'w').close()",+ " return {'status': 'ok', 'documents': []}",+ "isolated_worker._result = parse",+ "sys.argv = ['worker', 'unused', '.docx', "+ f"{str(isolated_loader.MAX_CHILD_DATA_BYTES)!r}, "+ f"{str(isolated_loader.CHILD_CPU_SECONDS)!r}, str(os.getpid())]",+ "raise SystemExit(isolated_worker.main())",+ ]+ )+ result = subprocess.run(+ [sys.executable, "-c", script],+ check=False,+ capture_output=True,+ timeout=60,+ )+ assert result.returncode == 0, result.stderr[-2000:]+ assert json.loads(result.stdout) == {"status": "error", "kind": "limit"}+ assert not parsed.exists()+++def test_parser_child_sends_no_unstructured_usage_request(monkeypatch):+ # Importing unstructured.logger sends a usage request to+ # packages.unstructured.io unless SCARF_NO_ANALYTICS or DO_NOT_TRACK is+ # exactly "true", and every parse imports it in a fresh child. Start+ # from a server environment whose opt-out does not work ("1" is not+ # "true"). The child's requests.get only records, so nothing is sent+ # even when the opt-out is missing.+ monkeypatch.setenv("SCARF_NO_ANALYTICS", "1")+ monkeypatch.delenv("DO_NOT_TRACK", raising=False)+ script = "\n".join(+ [+ "import json, os, requests",+ "calls = []",+ "requests.get = lambda *args, **kwargs: calls.append(args)",+ "import unstructured.logger",+ "result = {'calls': len(calls),",+ " 'opt_out': os.environ.get('SCARF_NO_ANALYTICS')}",+ "os.write(1, json.dumps(result).encode())",+ ]+ )+ output = isolated_loader._run_capped([sys.executable, "-c", script], 60)+ assert json.loads(output) == {"calls": 0, "opt_out": "true"}+++def _hide_nltk_data(directory: Path) -> list[str]:+ # Script lines that leave NLTK only an empty data directory and make+ # nltk.download record its calls, so nothing is fetched in any case.+ directory.mkdir()+ return [+ "import nltk",+ f"nltk.data.path[:] = [{str(directory)!r}]",+ "downloads = []",+ "nltk.download = lambda *args, **kwargs: downloads.append(args)",+ ]+++def test_parser_child_never_downloads_nltk_data(monkeypatch, tmp_path):+ # Importing unstructured downloads NLTK data that is missing, and every+ # parse imports it in a fresh child, where that download would run under+ # the parse deadline and outside any egress policy. Start from a server+ # environment that asks for the download.+ monkeypatch.setenv("AUTO_DOWNLOAD_NLTK", "true")+ script = "\n".join(+ [+ "import json, os",+ *_hide_nltk_data(tmp_path / "nltk_data"),+ "import unstructured.nlp.tokenize",+ "result = {'downloads': len(downloads),",+ " 'auto': os.environ.get('AUTO_DOWNLOAD_NLTK')}",+ "os.write(1, json.dumps(result).encode())",+ ]+ )+ output = isolated_loader._run_capped([sys.executable, "-c", script], 60)+ assert json.loads(output) == {"downloads": 0, "auto": "false"}+++def test_real_parse_without_nltk_data_reports_the_data_missing(tmp_path):+ # The real worker and registry loader in the production child+ # environment, with no NLTK data installed: a Word paragraph's text+ # classification needs it, and the parse must name that cause instead+ # of downloading the data or calling the document unreadable.+ source = tmp_path / "paragraph.docx"+ source.write_bytes(_docx_bytes())+ report = tmp_path / "downloads.json"+ script = "\n".join(+ [+ "import json, sys",+ *_hide_nltk_data(tmp_path / "nltk_data"),+ "from local_deep_research.security import isolated_worker",+ _worker_argv(str(source)),+ "code = isolated_worker.main()",+ f"with open({str(report)!r}, 'w') as handle:",+ " handle.write(json.dumps(len(downloads)))",+ "raise SystemExit(code)",+ ]+ )+ output = isolated_loader._run_capped([sys.executable, "-c", script], 90)+ assert json.loads(report.read_text()) == 0+ with pytest.raises(isolated_loader.ParserDataMissingError):+ isolated_loader._documents_from_output(output)+++ ("error", "kind"),+ [+ (LookupError("Resource 'punkt_tab' not found."), "nltk_data"),+ (+ LookupError("Resource 'averaged_perceptron_tagger_eng' not found."),+ "nltk_data",+ ),+ (LookupError("unknown encoding: punctuation"), "parser"),+ (KeyError("punkt_tab"), "parser"),+ ],+ ids=["tokenizer-data", "tagger-data", "other-lookup", "key-error"],+)+def test_worker_names_missing_nltk_data_only_for_nltks_error(+ monkeypatch, error, kind+):+ # nltk.data.find raises a plain LookupError naming the missing package.+ # Other lookups, KeyError included, are ordinary parser failures.+ class FailingLoader:+ def __init__(self, path, **kwargs):+ pass++ def load(self):+ raise error++ _stub_registry(monkeypatch, FailingLoader)+ assert isolated_worker._result("unused", ".docx") == {+ "status": "error",+ "kind": kind,+ }+++def test_missing_nltk_data_is_not_reported_as_an_unreadable_file(monkeypatch):+ monkeypatch.setattr(+ isolated_loader,+ "_run_capped",+ lambda *args, **kwargs: b'{"status": "error", "kind": "nltk_data"}',+ )+ # Unlike a refused document, which extracts as None, this says nothing+ # about the file, so the upload route can tell the operator the fix.+ with pytest.raises(+ isolated_loader.ParserDataMissingError, match="NLTK data"+ ):+ bytes_loader.extract_text_from_bytes(+ _docx_bytes(), ".docx", "nodata.docx"+ )+++def test_parser_child_starts_with_python_safe_path(monkeypatch):+ commands = []++ def record(command, timeout_s):+ commands.append(command)+ return _worker_output()++ monkeypatch.setattr(isolated_loader, "_run_capped", record)+ isolated_loader.load_documents_isolated("unused", ".docx")+ (command,) = commands+ assert command[: command.index("-m")] == [sys.executable, "-P"]+++ "entries",+ [["ROOT"], ["ROOT", ""], ["", "ROOT"], ["ROOT", "", ""]],+ ids=["named-only", "trailing-empty", "leading-empty", "two-empty"],+)+def test_parser_child_ignores_modules_in_the_working_directory(+ monkeypatch, tmp_path, entries+):+ # "python -m" puts its working directory first on sys.path, and the+ # child inherits the server's. A package there named like LDR would+ # then run instead of the worker for every parse. An empty PYTHONPATH+ # entry, as in PYTHONPATH=src:, also stands for that directory, even+ # under -P, and puts it before the standard library: a json.py there+ # would run in place of the json module the worker imports.+ workdir = tmp_path / "workdir"+ shadow = workdir / "local_deep_research" / "security"+ shadow.mkdir(parents=True)+ (workdir / "local_deep_research" / "__init__.py").write_text("")+ (shadow / "__init__.py").write_text("")+ (shadow / "isolated_worker.py").write_text(+ "import json, os\n"+ "documents = [{'page_content': 'working directory', 'metadata': {}}]\n"+ "os.write(1, json.dumps({'status': 'ok', 'documents': documents})"+ ".encode())\n"+ )+ imported = tmp_path / "json-imported"+ (workdir / "json.py").write_text(+ f"open({str(imported)!r}, 'w').close()\n"+ "raise ImportError('json.py from the working directory')\n"+ )+ archive = tmp_path / "saved.mht"+ archive.write_bytes(MHTML)+ # The child must still find the real package, wherever this test run+ # found it; a relative PYTHONPATH would resolve under the new directory.+ package_root = str(Path(isolated_loader.__file__).resolve().parents[2])+ monkeypatch.setenv(+ "PYTHONPATH",+ os.pathsep.join(+ package_root if entry == "ROOT" else entry for entry in entries+ ),+ )+ monkeypatch.chdir(workdir)+ documents = isolated_loader.load_documents_isolated(str(archive), ".mht")+ assert [doc.page_content.strip() for doc in documents] == ["hello mhtml"]+ assert not imported.exists()+++def test_default_parser_capacity_is_two(monkeypatch):+ # The other capacity tests swap in their own semaphore. This one uses+ # the module's, which the docs promise admits two parses at once.+ def forbidden(*args, **kwargs):+ raise AssertionError("parser launched beyond its capacity")++ monkeypatch.setattr(isolated_loader, "_run_capped", forbidden)+ slots = isolated_loader._parser_slots+ held = 0+ try:+ for _ in range(2):+ assert slots.acquire(blocking=False), "fewer than two slots"+ held += 1+ with pytest.raises(+ isolated_loader.IsolatedLoaderError, match="capacity"+ ):+ isolated_loader.load_documents_isolated("unused", ".docx")+ finally:+ for _ in range(held):+ slots.release()+++def test_busy_parser_is_not_reported_as_an_unreadable_file(monkeypatch):+ slots = threading.BoundedSemaphore(1)+ slots.acquire()+ monkeypatch.setattr(isolated_loader, "_parser_slots", slots)++ def forbidden(*args, **kwargs):+ raise AssertionError("saturated parser launched a child")++ monkeypatch.setattr(isolated_loader, "_run_capped", forbidden)+ # A valid upload reaching a saturated boundary says nothing about the+ # file, so the caller must be able to tell it from a refused document.+ with pytest.raises(isolated_loader.ParserBusyError, match="capacity"):+ bytes_loader.extract_text_from_bytes(+ _docx_bytes(), ".docx", "busy.docx"+ )+ slots.release()++ def timed_out(*args, **kwargs):+ raise isolated_loader.IsolatedLoaderError("document parser timed out")++ # Every other boundary failure is still a per-file extraction failure.+ monkeypatch.setattr(isolated_loader, "_run_capped", timed_out)+ assert (+ bytes_loader.extract_text_from_bytes(+ _docx_bytes(), ".docx", "slow.docx"+ )+ is None+ )++[email protected]("extension", [".mht", ".mhtml"])+def test_web_archives_parse_behind_the_boundary(monkeypatch, extension):+ # A saved web page's HTML parts go through the same parser stack as an+ # .html upload, so they must not be parsed in the server process.+ calls = []++ def isolated(path, ext):+ assert Path(path).read_bytes() == MHTML+ calls.append(ext)+ return [Document(page_content="archived", metadata={})]++ def in_process(*args, **kwargs):+ raise AssertionError("web archive parsed in the server process")++ monkeypatch.setattr(bytes_loader, "load_documents_isolated", isolated)+ monkeypatch.setattr(+ bytes_loader,+ "get_loader_class_for_extension",+ lambda ext: (in_process, {}),+ )+ documents = bytes_loader.load_from_bytes(+ MHTML, extension, f"saved{extension}"+ )+ assert calls == [extension]+ assert documents[0].page_content == "archived"+++def test_every_office_and_html_loader_runs_behind_the_boundary():+ # Sweep the registry rather than list extensions: a newly registered+ # extension with one of these parsers must be isolated too. Legacy+ # .doc/.ppt are converted to .docx/.pptx before this decision.+ from local_deep_research.document_loaders import loader_registry+ from local_deep_research.utilities.office_conversion import (+ is_legacy_office_extension,+ )++ bounded = {+ loader_registry.UnstructuredWordDocumentLoader,+ loader_registry.UnstructuredPowerPointLoader,+ loader_registry.UnstructuredExcelLoader,+ loader_registry.UnstructuredHTMLLoader,+ loader_registry.MHTMLLoader,+ loader_registry.XLSLoader,+ loader_registry.UnstructuredMarkdownLoader,+ loader_registry.UnstructuredEmailLoader,+ loader_registry.UnstructuredXMLLoader,+ loader_registry.EverNoteLoader,+ }+ unbounded = sorted(+ ext+ for ext, entry in loader_registry.LOADER_REGISTRY.items()+ if entry["loader_class"] in bounded+ and not is_legacy_office_extension(ext)+ and ext not in isolated_loader.ISOLATED_FINAL_EXTENSIONS+ )+ assert unbounded == []