From 6f0c7fdb478a2f7da73fcd8b406df32b4a8163fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=90=BD=E9=9B=A8=E2=9C=A6?= <1939566682@qq.com> Date: Mon, 24 Aug 2026 16:54:05 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20Windows=20MinerU=20parsing=20=E2=80=94?= =?UTF-8?q?=20subprocess=20UTF-8=20decoding=20&=20render-thread=20crash=20?= =?UTF-8?q?(#844)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: Windows robustness — MinerU UTF-8 decode, render-thread crash & atomic-write PermissionError - mineru/local.py: pass encoding="utf-8", errors="replace" to subprocess.Popen so MinerU's combined stdout/stderr is decoded as UTF-8 instead of the platform default (GBK on zh-CN Windows), which previously crashed with a UnicodeDecodeError (0x8b). - mineru/models.py: set MINERU_PDF_RENDER_THREADS=1 in model_env_overrides to avoid MinerU's multi-threaded PDF rendering heap-corruption crash (0xc0000409) on Windows. - services/file_io.py: retry atomic replace on transient PermissionError (e.g. target locked by antivirus/indexer) with exponential backoff, instead of failing the whole write on Windows. * fix(mineru): gate the render-thread guard to Windows `MINERU_PDF_RENDER_THREADS=1` was set unconditionally, but the variable is honored on Linux and macOS too (upstream default 3-4 render workers), so a Windows-only heap-corruption workaround was serializing page rendering for every platform. It also sat in `model_env_overrides`, whose contract is the model-weight download source — and adding a key there broke that function's exact-equality test. Move it to its own `render_env_overrides()` next to the other MinerU env knowledge, guarded on `sys.platform`, and merge it into the subprocess env at the local-CLI branch in `backend.py`. Only that branch renders pages in this process tree; cloud mode never does. --------- Co-authored-by: Frank --- deeptutor/services/file_io.py | 29 +++++++++++++++++-- .../parsing/engines/mineru/backend.py | 7 +++-- .../services/parsing/engines/mineru/local.py | 2 ++ .../services/parsing/engines/mineru/models.py | 15 ++++++++++ tests/tools/test_mineru_models.py | 20 +++++++++++++ 5 files changed, 69 insertions(+), 4 deletions(-) diff --git a/deeptutor/services/file_io.py b/deeptutor/services/file_io.py index 13018c7c7..bdf64c230 100644 --- a/deeptutor/services/file_io.py +++ b/deeptutor/services/file_io.py @@ -6,9 +6,34 @@ import json import os from pathlib import Path import tempfile +import time from typing import Any +def _atomic_replace(src: Path, dst: Path, *, max_retries: int = 5) -> None: + """Replace *dst* with *src*, retrying on transient ``PermissionError``. + + On Windows the destination file is occasionally locked by another process + (antivirus, indexer, or a concurrent reader), which makes ``Path.replace`` + raise ``PermissionError``. A short exponential backoff recovers in most + cases without losing the already-written content. + """ + delay = 0.2 + last_err: PermissionError | None = None + for attempt in range(max_retries): + try: + src.replace(dst) + return + except PermissionError as exc: # pragma: no cover - platform specific + last_err = exc + if attempt == max_retries - 1: + break + time.sleep(delay) + delay = min(delay * 2, 1.6) + assert last_err is not None + raise last_err + + def atomic_write_json(path: Path, payload: dict[str, Any]) -> None: """Write *payload* as UTF-8 JSON without exposing a partial target file.""" path = Path(path) @@ -29,7 +54,7 @@ def atomic_write_json(path: Path, payload: dict[str, Any]) -> None: os.fsync(handle.fileno()) except OSError: pass - temporary_path.replace(path) + _atomic_replace(temporary_path, path) finally: if temporary_path is not None: temporary_path.unlink(missing_ok=True) @@ -54,7 +79,7 @@ def atomic_write_text(path: Path, text: str) -> None: os.fsync(handle.fileno()) except OSError: pass - temporary_path.replace(path) + _atomic_replace(temporary_path, path) finally: if temporary_path is not None: temporary_path.unlink(missing_ok=True) diff --git a/deeptutor/services/parsing/engines/mineru/backend.py b/deeptutor/services/parsing/engines/mineru/backend.py index 328884517..ac3db2f09 100644 --- a/deeptutor/services/parsing/engines/mineru/backend.py +++ b/deeptutor/services/parsing/engines/mineru/backend.py @@ -124,7 +124,7 @@ def _parse_local( """Local-CLI branch: delegate to the existing subprocess parser and return the deterministic output directory it writes to (``/``).""" from .local import parse_pdf_with_mineru - from .models import model_env_overrides + from .models import model_env_overrides, render_env_overrides cli_command = None if (config.local_cli_path or "").strip(): @@ -139,6 +139,9 @@ def _parse_local( # A lazy first-parse model download must honor the configured source and # custom address, not just the explicit Download button. download_env = model_env_overrides(config.model_download_source, config.model_download_endpoint) + # Only the local CLI renders pages in this process tree; cloud mode never + # does, so the Windows render-thread guard belongs on this branch alone. + subprocess_env = {**download_env, **render_env_overrides()} logger.info("Parsing %s via local MinerU CLI (%s)", pdf_path.name, cli_command or "PATH") ok = parse_pdf_with_mineru( @@ -146,7 +149,7 @@ def _parse_local( str(output_base), on_output=on_output, cli_command=cli_command, - extra_env=download_env, + extra_env=subprocess_env, ) if not ok: raise MinerUError( diff --git a/deeptutor/services/parsing/engines/mineru/local.py b/deeptutor/services/parsing/engines/mineru/local.py index 08b580234..066cd3eb5 100644 --- a/deeptutor/services/parsing/engines/mineru/local.py +++ b/deeptutor/services/parsing/engines/mineru/local.py @@ -139,6 +139,8 @@ def parse_pdf_with_mineru( stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, + encoding="utf-8", + errors="replace", shell=False, env={**os.environ, **extra_env} if extra_env else None, ) diff --git a/deeptutor/services/parsing/engines/mineru/models.py b/deeptutor/services/parsing/engines/mineru/models.py index 81039e913..d763a5c59 100644 --- a/deeptutor/services/parsing/engines/mineru/models.py +++ b/deeptutor/services/parsing/engines/mineru/models.py @@ -20,6 +20,7 @@ import os from pathlib import Path import shutil import subprocess +import sys import threading import time from typing import Any @@ -71,6 +72,20 @@ def model_env_overrides(source: str, endpoint: str = "") -> dict[str, str]: return overrides +def render_env_overrides() -> dict[str, str]: + """Env vars that steer how MinerU renders PDF pages to images. + + MinerU renders pages with several worker threads (``MINERU_PDF_RENDER_THREADS``, + upstream default 3-4). On Windows that concurrency can abort the parse + process with a heap-corruption fault (0xc0000409), so serialize it there. + The variable is honored on every platform, hence the explicit guard: Linux + and macOS keep the parallel renderer and its throughput. + """ + if sys.platform != "win32": + return {} + return {"MINERU_PDF_RENDER_THREADS": "1"} + + class ModelDownloadManager: """At most one model-download subprocess, with a cursor-based line log. diff --git a/tests/tools/test_mineru_models.py b/tests/tools/test_mineru_models.py index e4595f1f8..5913e081c 100644 --- a/tests/tools/test_mineru_models.py +++ b/tests/tools/test_mineru_models.py @@ -10,6 +10,7 @@ from deeptutor.services.parsing.engines.mineru import models as mineru_models from deeptutor.services.parsing.engines.mineru.models import ( ModelDownloadManager, model_env_overrides, + render_env_overrides, resolve_models_downloader, ) @@ -173,3 +174,22 @@ def test_manager_rejects_concurrent_start_and_cancels( def test_manager_cancel_without_job() -> None: assert ModelDownloadManager().cancel()["ok"] is False + + +def test_render_env_overrides_is_windows_only(monkeypatch) -> None: + """The render-thread guard must not slow Linux/macOS. + + ``MINERU_PDF_RENDER_THREADS`` is honored on every platform (upstream + default 3-4 workers), so serializing it unconditionally would cost every + non-Windows user parse throughput for a Windows-only heap-corruption crash. + """ + import deeptutor.services.parsing.engines.mineru.models as models + + monkeypatch.setattr(models.sys, "platform", "win32") + assert render_env_overrides() == {"MINERU_PDF_RENDER_THREADS": "1"} + + monkeypatch.setattr(models.sys, "platform", "linux") + assert render_env_overrides() == {} + + monkeypatch.setattr(models.sys, "platform", "darwin") + assert render_env_overrides() == {}