DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix: Windows MinerU parsing — subprocess UTF-8 decoding & render-thread crash (#844)
落雨✦6f0c7fdb478a
diff --git a/deeptutor/services/file_io.py b/deeptutor/services/file_io.pyindex 13018c7c7..bdf64c230 100644--- a/deeptutor/services/file_io.py+++ b/deeptutor/services/file_io.py@@ -6,9 +6,34 @@ import jsonimport osfrom pathlib import Pathimport tempfile+import timefrom 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.pyindex 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 returnthe deterministic output directory it writes to (``<base>/<stem>``)."""from .local import parse_pdf_with_mineru- from .models import model_env_overrides+ from .models import model_env_overrides, render_env_overridescli_command = Noneif (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.pyindex 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.pyindex 81039e913..d763a5c59 100644--- a/deeptutor/services/parsing/engines/mineru/models.py+++ b/deeptutor/services/parsing/engines/mineru/models.py@@ -20,6 +20,7 @@ import osfrom pathlib import Pathimport shutilimport subprocess+import sysimport threadingimport timefrom 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.pyindex 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_modelsfrom 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() == {}