Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

Add memory benchmarking script and enhance memory management features

myhlolib65dbbac9772
diff --git a/docs/en/usage/cli_tools.md b/docs/en/usage/cli_tools.md
index 8183f271..d27c0781 100644
--- a/docs/en/usage/cli_tools.md
+++ b/docs/en/usage/cli_tools.md
@@ -70,6 +70,7 @@ mineru-kit vlm-server --engine auto --port 30000
- `MINERU_API_ENABLE_FASTAPI_DOCS`: enable `/docs`, `/openapi.json`, and `/redoc` on the V1 API server; default `true`.
- `MINERU_PDF_RENDER_TIMEOUT` / `MINERU_PDF_RENDER_THREADS`: PDF rendering timeout and worker count.
- `MINERU_PROCESSING_WINDOW_SIZE`: processing window size used for large documents. Flash native text parsing renders only pages with visual blocks, preserving this window boundary, rendering timeout, and worker settings. A 32 MiB pixel budget can split batches further. OCR and other tiers still render entire windows.
+- `MINERU_MALLOC_TRIM`: disabled by default; only `1/true/yes/on` enable it, ignoring case and surrounding whitespace. On Linux, when available, it attempts to return the current process's free glibc heap pages after inference windows and PDF document cleanup. Flash native parsing only attempts trimming at document completion. Unsupported platforms or missing symbols are a no-op. It does not release live objects, GPU memory, or render-worker memory. See [memory benchmarking](./pdf_memory.md).
- `MINERU_INTRA_OP_NUM_THREADS` / `MINERU_INTER_OP_NUM_THREADS`: ONNX operator thread settings.
Prefer each command's `--help` output and [model source documentation](./model_source.md) for current defaults.
diff --git a/docs/en/usage/pdf_memory.md b/docs/en/usage/pdf_memory.md
new file mode 100644
index 00000000..58d52612
--- /dev/null
+++ b/docs/en/usage/pdf_memory.md
@@ -0,0 +1,39 @@
+# PDF memory regression checks
+
+Window lifetime improvements are always active. `MINERU_MALLOC_TRIM` independently enables optional CPU heap trimming and is off by default. Measure real workloads on Linux/glibc before claiming an RSS improvement or an OOM fix; macOS checks cannot establish either.
+
+## Compare three configurations
+
+Use the same host, Python environment, DocVortex version, models, settings, and concurrency. Create a separate worktree at the pre-change commit without switching or overwriting your development checkout.
+
+Activate the project Python environment and install the diagnostic-only dependency with `uv pip install psutil`. Run the updated script from your development checkout. `--repo` selects the child process's MinerU source; third-party dependencies still come from the current Python environment.
+
+```bash
+python scripts/benchmark_pdf_memory.py --repo /tmp/mineru-memory-baseline --pdf demo/pdfs/demo1.pdf demo/pdfs/demo2.pdf --tier basic --mode ocr --window-size 2 --trim 0 --output /tmp/mineru-memory-before
+python scripts/benchmark_pdf_memory.py --pdf demo/pdfs/demo1.pdf demo/pdfs/demo2.pdf --tier basic --mode ocr --window-size 2 --trim 0 --output /tmp/mineru-memory-after-off
+python scripts/benchmark_pdf_memory.py --pdf demo/pdfs/demo1.pdf demo/pdfs/demo2.pdf --tier basic --mode ocr --window-size 2 --trim 1 --output /tmp/mineru-memory-after-on
+```
+
+Each group starts a fresh parser process, warms up for three rounds, and measures twenty rounds. One document is processed per round, cycling through multiple inputs in order and releasing the preceding result. Output directories must not already exist.
+
+- For repeated-document checks, pass one PDF. For alternating documents, pass two or more.
+- For multiple windows, use a document longer than `--window-size`. This affects only the experiment, not product defaults.
+- Exercise `basic/standard/advanced` with `txt/ocr`, plus `flash --mode ocr`, using the required models and VLM configuration.
+- Without neural models, `flash --mode txt` can validate the harness, document cleanup, and selective rendering. It cannot validate inference-window allocation lifetimes or inference performance.
+
+## Outputs and interpretation
+
+- `rounds.jsonl`: input, page count, parse duration, and timestamps per round, marking warmup rounds.
+- `samples.jsonl`: externally sampled RSS/USS for the parser and all child PIDs every 0.2 seconds. Unavailable USS is `null`; change frequency with `--interval`.
+- `parse.log`: production logs with window ranges and render-worker PIDs for correlation.
+- `summary.json`: measured-round median parse time, per-PID peaks, and simultaneous process-total peaks. Summed RSS can double-count shared pages, and sampling can miss brief peaks.
+
+Inspect the parent and workers separately. Compare post-warmup trends, plateaus, peaks, and timing. Investigate a median slowdown above 5% with trimming disabled after excluding concurrent workloads, cold model startup, and sampling noise. Report enabled-trim overhead separately and repeat the complete experiment before drawing conclusions.
+
+Trimming cannot release live results, model caches, other allocators' pools, another process's memory, or objects still referenced by exception tracebacks. DocVortex worker reclamation is outside this change.
+
+## Output parity
+
+In separate output directories, add `--warmup 0 --rounds 2 --fingerprints` to each configuration. Compare `middle_sha256` and `model_sha256` for matching inputs; hashes include full asset fields. Fingerprinting performs extra serialization, so do not use these runs for memory or performance conclusions.
+
+If Linux, models, or USS access are unavailable, record that limitation explicitly and keep trimming disabled by default.
diff --git a/docs/zh/usage/cli_tools.md b/docs/zh/usage/cli_tools.md
index 2edb68a7..a93d44f9 100644
--- a/docs/zh/usage/cli_tools.md
+++ b/docs/zh/usage/cli_tools.md
@@ -70,6 +70,7 @@ mineru-kit vlm-server --engine auto --port 30000
- `MINERU_API_ENABLE_FASTAPI_DOCS`:是否为 V1 API Server 启用 `/docs`、`/openapi.json` 和 `/redoc`,默认 `true`。
- `MINERU_PDF_RENDER_TIMEOUT` / `MINERU_PDF_RENDER_THREADS`:PDF 渲染超时和 worker 数量。
- `MINERU_PROCESSING_WINDOW_SIZE`:大文档处理窗口大小。Flash 原生文本路径仅渲染有视觉块的页面,仍遵守该窗口边界、渲染超时和 worker 配置,并按 32 MiB 像素预算进一步分批。OCR 和其他档位保持整窗口渲染。
+- `MINERU_MALLOC_TRIM`:默认关闭;仅 `1/true/yes/on` 启用,忽略大小写和首尾空白。Linux 上可用时,在推理窗口及 PDF 文档清理后尝试归还当前进程的 glibc 空闲堆页;Flash 原生路径仅在文档结束时尝试。其他平台或缺少符号时为空操作,不释放存活对象、GPU 显存或渲染子进程内存。参见[内存压测方法](./pdf_memory.md)。
- `MINERU_INTRA_OP_NUM_THREADS` / `MINERU_INTER_OP_NUM_THREADS`:ONNX 算子线程配置。
当前默认值以各命令的 `--help` 和[模型源说明](./model_source.md)为准。
diff --git a/docs/zh/usage/pdf_memory.md b/docs/zh/usage/pdf_memory.md
new file mode 100644
index 00000000..143a6bd0
--- /dev/null
+++ b/docs/zh/usage/pdf_memory.md
@@ -0,0 +1,40 @@
+# PDF 内存回归验证
+
+窗口生命周期修复始终生效。`MINERU_MALLOC_TRIM` 是独立的可选 CPU 堆回收开关,默认关闭。只有在 Linux/glibc 上完成真实测量,才能判断它是否改善当前负载;macOS 上的通过结果不证明 Linux RSS 收益或 OOM 已解决。
+
+## 对比方法
+
+在同一主机、Python 环境、DocVortex 版本、模型配置和并发条件下比较修复前、修复后关闭 trim、修复后开启 trim。先创建修复前提交的独立 worktree。不要切换或覆盖正在开发的工作区。
+
+激活项目 Python 环境,安装仅供诊断脚本使用的 `psutil`(`uv pip install psutil`)。从修复后的工作区执行下面三组实验;`--repo` 只切换子进程的 MinerU 源码,第三方依赖共用当前 Python 环境。
+
+```bash
+python scripts/benchmark_pdf_memory.py --repo /tmp/mineru-memory-baseline --pdf demo/pdfs/demo1.pdf demo/pdfs/demo2.pdf --tier basic --mode ocr --window-size 2 --trim 0 --output /tmp/mineru-memory-before
+python scripts/benchmark_pdf_memory.py --pdf demo/pdfs/demo1.pdf demo/pdfs/demo2.pdf --tier basic --mode ocr --window-size 2 --trim 0 --output /tmp/mineru-memory-after-off
+python scripts/benchmark_pdf_memory.py --pdf demo/pdfs/demo1.pdf demo/pdfs/demo2.pdf --tier basic --mode ocr --window-size 2 --trim 1 --output /tmp/mineru-memory-after-on
+```
+
+每组使用独立解析进程,默认预热 3 轮、测量 20 轮。每轮处理一个文件,多个输入依次循环;上一轮的 ParseResult 会在下一轮前释放。输出目录必须不存在,避免覆盖历史数据。
+
+- 重复同一文档:只传一个 `--pdf` 输入。
+- 交替不同文档:传两个或更多输入。
+- 多窗口文档:使用页数大于 `--window-size` 的文件。窗口大小只影响本次实验,不改变产品默认配置。
+- 推理路径分别运行 `basic/standard/advanced` 与 `txt/ocr`,以及 `flash --mode ocr`;需要对应模型和 VLM 配置。
+- 没有神经模型时可以先用 `flash --mode txt` 验证脚本、文档级清理和按需补图,但不能据此验证推理窗口的大数组生命周期或推理性能。
+
+## 输出与判断
+
+- `rounds.jsonl`:每轮输入、页数、解析耗时和起止时刻,区分预热与测量。
+- `samples.jsonl`:外部每 0.2 秒采样的主进程及全部子进程 RSS/USS,保留 PID。USS 不可读取时记录 `null`;可用 `--interval` 调整频率。
+- `parse.log`:生产解析日志,包含窗口页码以及渲染 worker PID,可用于关联采样。
+- `summary.json`:测量阶段耗时中位数、各 PID 峰值和同一采样时刻的进程合计峰值。RSS 合计可能重复计算共享页;采样峰值也可能遗漏短暂尖峰,不能视为精确最高水位。
+
+主进程和 worker 分别检查,避免把子进程滞留误认为主进程 trim 无效。观察预热后各轮结束附近的 RSS/USS 是否持续增长、是否稳定到平台,以及峰值与耗时变化。基线与修复后关闭 trim 的耗时中位数若回归超过 5%,在排除并行任务、模型冷启动和采样噪声后调查;启用 trim 的成本单独记录。建议重复完整三组实验,避免凭单次结果下结论。
+
+`malloc_trim` 不回收存活结果、模型缓存、其他分配器的池或其他进程的内存。异常栈仍引用的对象也可能继续存活。本轮不修改 DocVortex worker 的回收策略。
+
+## 结果一致性
+
+使用单独输出目录为三组命令追加 `--warmup 0 --rounds 2 --fingerprints`。比较相同输入的 `middle_sha256` 和 `model_sha256`,摘要包含完整素材字段。`--fingerprints` 额外执行序列化,因此不要用这一组数据评估内存和性能。
+
+只有完成真实 Linux 推理负载测量后,才报告对应场景的 RSS 改善。缺少环境、模型或无法获取 USS 时,应在验收记录中明确说明,不将默认开关改为开启。
diff --git a/mineru/backend/analysis/pdf/pipeline.py b/mineru/backend/analysis/pdf/pipeline.py
index f4f47a3f..4eae83f9 100644
--- a/mineru/backend/analysis/pdf/pipeline.py
+++ b/mineru/backend/analysis/pdf/pipeline.py
@@ -9,7 +9,7 @@ from typing import Any, cast
from ..contracts import AnalysisResult, AnalyzeEffort, ParseMode, ResolvedParseMode
from ....config import VlmConfig
from ....model.runtime.hybrid import HybridLocalModelContextSingleton
-from ....model.runtime.memory import clean_memory
+from ....model.runtime.memory import clean_memory, trim_process_heap
from ....model.vlm.client import get_vlm_predictor
from docvortex.document.pdf.document import PDFDocument
@@ -74,9 +74,13 @@ def analyze_pdf(
try:
document.close()
finally:
- # 无论窗口处理是否异常,都释放已初始化的 Hybrid 模型资源。
- if hybrid_model is not None:
- clean_memory(hybrid_model.device)
+ try:
+ # 无论窗口处理是否异常,都释放已初始化的 Hybrid 模型资源。
+ if hybrid_model is not None:
+ clean_memory(hybrid_model.device)
+ finally:
+ # Flash TXT 同样覆盖 CPU 堆回收,但不因此加载 Torch 或模型。
+ trim_process_heap()
return AnalysisResult(
model_list=model_list,
diff --git a/mineru/backend/analysis/pdf/window.py b/mineru/backend/analysis/pdf/window.py
index 5923ac43..4b7c58d1 100644
--- a/mineru/backend/analysis/pdf/window.py
+++ b/mineru/backend/analysis/pdf/window.py
@@ -10,6 +10,7 @@ import numpy as np
from loguru import logger
from ....model.runtime.hybrid import HybridLocalModelContext
+from ....model.runtime.memory import trim_process_heap
from docvortex.document.pdf.document import PDFDocument
from docvortex.document.pdf.document import PDFPage
from docvortex.document.pdf.document import PDFPageTextGeometry
@@ -282,6 +283,194 @@ def _process_text_and_formulas(
)
+def _process_pdf_window(
+ file_bytes: bytes,
+ document: PDFDocument,
+ window: _ProcessingWindow,
+ *,
+ page_count: int,
+ effort: AnalyzeEffort,
+ parse_mode: Literal["txt", "ocr"],
+ image_analysis: bool,
+ hybrid_model: HybridLocalModelContext | None,
+ vlm_predictor: Any,
+) -> list[list[dict[str, Any]]]:
+ """在独立作用域完成单窗口分析与裁图,关闭页图并解除本层临时数组引用。"""
+ images_list: list[dict[str, Any]] = []
+ images_pil_list = []
+ np_images = []
+ table_items = []
+ try:
+ window_pages = _get_window_pdf_pages(document, window)
+ images_list = load_images_from_pdf_bytes_range(
+ pdf_bytes=file_bytes,
+ start_page_id=window.start,
+ end_page_id=window.end,
+ image_type="pil_img",
+ )
+ if len(window_pages) != len(images_list):
+ raise ValueError("Hybrid processing window PDF page count does not match image count")
+ images_pil_list = [image_dict["img_pil"] for image_dict in images_list]
+ _log_processing_window(window, page_count, len(images_pil_list))
+ page_text_geometries: list[PDFPageTextGeometry | None] | None = (
+ [None] * len(window_pages) if parse_mode == "txt" and effort in {"medium", "high", "xhigh"} else None
+ )
+
+ local_model_context = hybrid_model
+ if local_model_context is None:
+ raise ValueError("Hybrid local model context is required outside Flash TXT mode")
+ np_images = [np.asarray(pil_image).copy() for pil_image in images_pil_list]
+ images_layout_res = local_model_context.layout_model.batch_predict(
+ images_pil_list, batch_size=min(8, BATCH_RATIO * LAYOUT_BASE_BATCH_SIZE)
+ )
+
+ # 使用小模型layout时对layout的表格做旋转检测
+ if effort in ["flash", "medium", "high"]:
+ table_items = _collect_table_items(images_layout_res, np_images)
+ if table_items:
+ _apply_table_orientations(
+ table_items,
+ parse_mode,
+ window_pages,
+ images_list,
+ local_model_context,
+ )
+
+ vl_style_layout_blocks = _build_vl_style_layout_blocks(images_layout_res, images_pil_list)
+
+ if parse_mode == "txt" and effort in {"medium", "high"}:
+ native_table_summary = _apply_native_txt_table_priority(
+ vl_style_layout_blocks,
+ images_layout_res,
+ window_pages,
+ images_list,
+ effort=effort,
+ page_text_geometries=page_text_geometries,
+ )
+ if native_table_summary.total:
+ native_table_stats = {
+ "effort": effort,
+ "total": native_table_summary.total,
+ "accepted": native_table_summary.accepted,
+ "complex_fallbacks": native_table_summary.complex_fallbacks,
+ "rejected": native_table_summary.rejected,
+ "errors": native_table_summary.errors,
+ "removed_internal_text": native_table_summary.removed_internal_text,
+ "removed_formula_blocks": native_table_summary.removed_formula_blocks,
+ "removed_formula_layout_items": native_table_summary.removed_formula_layout_items,
+ }
+ logger.bind(native_table_priority=native_table_stats).info(
+ "Hybrid native table priority. "
+ f"effort={native_table_stats['effort']}, total={native_table_stats['total']}, "
+ f"accepted={native_table_stats['accepted']}, "
+ f"complex_fallbacks={native_table_stats['complex_fallbacks']}, "
+ f"rejected={native_table_stats['rejected']}, "
+ f"errors={native_table_stats['errors']}, "
+ f"removed_internal_text={native_table_stats['removed_internal_text']}, "
+ f"removed_formula_blocks={native_table_stats['removed_formula_blocks']}, "
+ f"removed_formula_layout_items={native_table_stats['removed_formula_layout_items']}"
+ )
+
+ if parse_mode == "txt":
+ if effort == "medium":
+ window_model_list = vl_style_layout_blocks
+ elif effort == "high":
+ high_vlm_blocks, accepted_native_tables = _split_native_high_table_blocks(vl_style_layout_blocks)
+ high_vlm_results = vlm_predictor.batch_extract_with_layout(
+ images=images_pil_list,
+ blocks_list=high_vlm_blocks,
+ not_extract_list=NOT_EXTRACT_TYPES,
+ image_analysis=False,
+ )
+ window_model_list = _restore_native_high_table_blocks(
+ high_vlm_results,
+ accepted_native_tables,
+ )
+ elif effort == "xhigh":
+ window_model_list = vlm_predictor.batch_two_step_extract(
+ images=images_pil_list,
+ not_extract_list=NOT_EXTRACT_TYPES,
+ image_analysis=image_analysis,
+ )
+ else:
+ raise ValueError(f"Unsupported analyze effort: {effort}")
+ elif parse_mode == "ocr":
+ if effort in ["flash", "medium"]:
+ window_model_list = vl_style_layout_blocks
+ elif effort == "high":
+ window_model_list = vlm_predictor.batch_extract_with_layout(
+ images=images_pil_list,
+ blocks_list=vl_style_layout_blocks,
+ image_analysis=False,
+ )
+ elif effort == "xhigh":
+ window_model_list = vlm_predictor.batch_two_step_extract(
+ images=images_pil_list,
+ image_analysis=image_analysis,
+ )
+ else:
+ raise ValueError(f"Unsupported analyze effort: {effort}")
+ else:
+ raise ValueError(f"Unsupported parse mode: {parse_mode}")
+
+ if effort in {"high", "xhigh"}:
+ window_model_list = _convert_vlm_results_to_model_list(window_model_list)
+ if effort == "xhigh":
+ _normalize_xhigh_vlm_blocks(window_model_list)
+ _apply_layout_title_split(
+ window_model_list,
+ images_layout_res,
+ [_normalize_page_size(image) for image in images_pil_list],
+ )
+
+ if effort == "flash":
+ window_model_list = _process_flash_ocr(
+ images_list,
+ window_pages,
+ window_model_list,
+ local_model_context,
+ images_layout_res,
+ )
+ # Flash OCR 在表内对象清理后复用统一公式编号合并,确保视觉裁图包含编号区域。
+ for page_model_list in window_model_list:
+ page_model_list[:] = optimize_hybrid_formula_number_blocks(page_model_list)
+ else:
+ window_model_list = _process_text_and_formulas(
+ images_list,
+ window_pages,
+ window_model_list,
+ parse_mode,
+ effort,
+ local_model_context,
+ images_layout_res,
+ page_text_geometries,
+ )
+
+ if effort in {"medium", "high"}:
+ _apply_seal_ocr(local_model_context, window_model_list, np_images)
+ elif effort == "xhigh":
+ _supplement_missing_image_block_containers(
+ window_model_list,
+ vl_style_layout_blocks,
+ )
+
+ _attach_visual_block_images(
+ window_model_list,
+ images_list,
+ page_start_index=window.start,
+ )
+ return window_model_list
+ finally:
+ try:
+ _close_images(images_list)
+ finally:
+ # 仅清空临时图像容器;结果中的 block、布局字典和物化素材可能共享,不能清空。
+ table_items.clear()
+ np_images.clear()
+ images_pil_list.clear()
+ images_list.clear()
+
+
def process_pdf_windows(
file_bytes: bytes,
document: PDFDocument,
@@ -315,169 +504,22 @@ def process_pdf_windows(
_log_processing_window_plan(page_count, configured_window_size, len(windows))
for window in windows:
- window_pages = _get_window_pdf_pages(document, window)
- images_list = load_images_from_pdf_bytes_range(
- pdf_bytes=file_bytes,
- start_page_id=window.start,
- end_page_id=window.end,
- image_type="pil_img",
- )
try:
- if len(window_pages) != len(images_list):
- raise ValueError("Hybrid processing window PDF page count does not match image count")
- images_pil_list = [image_dict["img_pil"] for image_dict in images_list]
- _log_processing_window(window, page_count, len(images_pil_list))
- page_text_geometries: list[PDFPageTextGeometry | None] | None = (
- [None] * len(window_pages)
- if parse_mode == "txt" and effort in {"medium", "high", "xhigh"}
- else None
- )
-
- local_model_context = hybrid_model
- if local_model_context is None:
- raise ValueError("Hybrid local model context is required outside Flash TXT mode")
- np_images = [np.asarray(pil_image).copy() for pil_image in images_pil_list]
- images_layout_res = local_model_context.layout_model.batch_predict(
- images_pil_list, batch_size=min(8, BATCH_RATIO * LAYOUT_BASE_BATCH_SIZE)
- )
-
- # 使用小模型layout时对layout的表格做旋转检测
- if effort in ["flash", "medium", "high"]:
- table_items = _collect_table_items(images_layout_res, np_images)
- if table_items:
- _apply_table_orientations(
- table_items,
- parse_mode,
- window_pages,
- images_list,
- local_model_context,
- )
-
- vl_style_layout_blocks = _build_vl_style_layout_blocks(images_layout_res, images_pil_list)
-
- if parse_mode == "txt" and effort in {"medium", "high"}:
- native_table_summary = _apply_native_txt_table_priority(
- vl_style_layout_blocks,
- images_layout_res,
- window_pages,
- images_list,
+ model_list.extend(
+ _process_pdf_window(
+ file_bytes,
+ document,
+ window,
+ page_count=page_count,
effort=effort,
- page_text_geometries=page_text_geometries,
- )
- if native_table_summary.total:
- native_table_stats = {
- "effort": effort,
- "total": native_table_summary.total,
- "accepted": native_table_summary.accepted,
- "complex_fallbacks": native_table_summary.complex_fallbacks,
- "rejected": native_table_summary.rejected,
- "errors": native_table_summary.errors,
- "removed_internal_text": native_table_summary.removed_internal_text,
- "removed_formula_blocks": native_table_summary.removed_formula_blocks,
- "removed_formula_layout_items": native_table_summary.removed_formula_layout_items,
- }
- logger.bind(native_table_priority=native_table_stats).info(
- "Hybrid native table priority. "
- f"effort={native_table_stats['effort']}, total={native_table_stats['total']}, "
- f"accepted={native_table_stats['accepted']}, "
- f"complex_fallbacks={native_table_stats['complex_fallbacks']}, "
- f"rejected={native_table_stats['rejected']}, "
- f"errors={native_table_stats['errors']}, "
- f"removed_internal_text={native_table_stats['removed_internal_text']}, "
- f"removed_formula_blocks={native_table_stats['removed_formula_blocks']}, "
- f"removed_formula_layout_items={native_table_stats['removed_formula_layout_items']}"
- )
-
- if parse_mode == "txt":
- if effort == "medium":
- window_model_list = vl_style_layout_blocks
- elif effort == "high":
- high_vlm_blocks, accepted_native_tables = _split_native_high_table_blocks(vl_style_layout_blocks)
- high_vlm_results = vlm_predictor.batch_extract_with_layout(
- images=images_pil_list,
- blocks_list=high_vlm_blocks,
- not_extract_list=NOT_EXTRACT_TYPES,
- image_analysis=False,
- )
- window_model_list = _restore_native_high_table_blocks(
- high_vlm_results,
- accepted_native_tables,
- )
- elif effort == "xhigh":
- window_model_list = vlm_predictor.batch_two_step_extract(
- images=images_pil_list,
- not_extract_list=NOT_EXTRACT_TYPES,
- image_analysis=image_analysis,
- )
- else:
- raise ValueError(f"Unsupported analyze effort: {effort}")
- elif parse_mode == "ocr":
- if effort in ["flash", "medium"]:
- window_model_list = vl_style_layout_blocks
- elif effort == "high":
- window_model_list = vlm_predictor.batch_extract_with_layout(
- images=images_pil_list,
- blocks_list=vl_style_layout_blocks,
- image_analysis=False,
- )
- elif effort == "xhigh":
- window_model_list = vlm_predictor.batch_two_step_extract(
- images=images_pil_list,
- image_analysis=image_analysis,
- )
- else:
- raise ValueError(f"Unsupported analyze effort: {effort}")
- else:
- raise ValueError(f"Unsupported parse mode: {parse_mode}")
-
- if effort in {"high", "xhigh"}:
- window_model_list = _convert_vlm_results_to_model_list(window_model_list)
- if effort == "xhigh":
- _normalize_xhigh_vlm_blocks(window_model_list)
- _apply_layout_title_split(
- window_model_list,
- images_layout_res,
- [_normalize_page_size(image) for image in images_pil_list],
- )
-
- if effort == "flash":
- window_model_list = _process_flash_ocr(
- images_list,
- window_pages,
- window_model_list,
- local_model_context,
- images_layout_res,
+ parse_mode=parse_mode,
+ image_analysis=image_analysis,
+ hybrid_model=hybrid_model,
+ vlm_predictor=vlm_predictor,
)
- # Flash OCR 在表内对象清理后复用统一公式编号合并,确保视觉裁图包含编号区域。
- for page_model_list in window_model_list:
- page_model_list[:] = optimize_hybrid_formula_number_blocks(page_model_list)
- else:
- window_model_list = _process_text_and_formulas(
- images_list,
- window_pages,
- window_model_list,
- parse_mode,
- effort,
- local_model_context,
- images_layout_res,
- page_text_geometries,
- )
-
- if effort in {"medium", "high"}:
- _apply_seal_ocr(local_model_context, window_model_list, np_images)
- elif effort == "xhigh":
- _supplement_missing_image_block_containers(
- window_model_list,
- vl_style_layout_blocks,
- )
-
- _attach_visual_block_images(
- window_model_list,
- images_list,
- page_start_index=window.start,
)
- model_list.extend(window_model_list)
finally:
- _close_images(images_list)
+ # 单窗口作用域退出后再回收,避免上一窗口临时数组与下一窗口渲染重叠。
+ trim_process_heap()
return model_list
diff --git a/mineru/model/runtime/memory.py b/mineru/model/runtime/memory.py
index 4509dcf0..1eb772c0 100644
--- a/mineru/model/runtime/memory.py
+++ b/mineru/model/runtime/memory.py
@@ -5,11 +5,42 @@ from __future__ import annotations
import gc
import os
+import sys
+from collections.abc import Callable
+from functools import lru_cache
from typing import Any
from loguru import logger
+@lru_cache(maxsize=1)
+def _get_malloc_trim() -> Callable[[int], int] | None:
+ """首次启用时解析并缓存 libc 回收函数,缺失能力时缓存空结果。"""
+ try:
+ import ctypes
+
+ malloc_trim = ctypes.CDLL(None).malloc_trim
+ malloc_trim.argtypes = [ctypes.c_size_t]
+ malloc_trim.restype = ctypes.c_int
+ return malloc_trim
+ except Exception:
+ return None
+
+
+def trim_process_heap() -> bool:
+ """按显式开关尽力归还当前 Linux 进程的空闲堆页,不加载模型或执行垃圾回收。"""
+ if os.getenv("MINERU_MALLOC_TRIM", "").strip().lower() not in {"1", "true", "yes", "on"}:
+ return False
+ if not sys.platform.startswith("linux"):
+ return False
+ try:
+ malloc_trim = _get_malloc_trim()
+ return bool(malloc_trim(0)) if malloc_trim is not None else False
+ except Exception:
+ # 可选回收失败不得覆盖解析或资源关闭阶段的原始异常。
+ return False
+
+
def _optional_torch() -> tuple[Any | None, Any | None]:
"""惰性加载 torch 与可选 NPU 扩展,避免公共门面触发重依赖。"""
try:
@@ -82,4 +113,4 @@ def get_vram(device: str) -> int:
return 1
-__all__ = ["clean_memory", "get_vram"]
+__all__ = ["clean_memory", "get_vram", "trim_process_heap"]
diff --git a/scripts/benchmark_pdf_memory.py b/scripts/benchmark_pdf_memory.py
new file mode 100644
index 00000000..58bd4a43
--- /dev/null
+++ b/scripts/benchmark_pdf_memory.py
@@ -0,0 +1,219 @@
+"""在独立解析进程外采样内存,比较不同 checkout 与堆回收开关的效果。"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import importlib.metadata
+import json
+import os
+import platform
+import statistics
+import subprocess
+import sys
+import time
+from pathlib import Path
+from typing import Any
+
+
+def _arguments() -> argparse.Namespace:
+ """读取诊断参数,默认预热三轮并测量二十轮,输入文件按顺序循环。"""
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--repo", type=Path, default=Path(__file__).resolve().parents[1])
+ parser.add_argument("--pdf", type=Path, nargs="+", required=True)
+ parser.add_argument("--output", type=Path, required=True)
+ parser.add_argument("--tier", choices=("flash", "basic", "standard", "advanced"), default="flash")
+ parser.add_argument("--mode", choices=("txt", "ocr", "auto"), default="txt")
+ parser.add_argument("--trim", choices=("0", "1"), default="0")
+ parser.add_argument("--warmup", type=int, default=3)
+ parser.add_argument("--rounds", type=int, default=20)
+ parser.add_argument("--interval", type=float, default=0.2)
+ parser.add_argument("--window-size", type=int, default=64)
+ parser.add_argument(
+ "--fingerprints", action="store_true", help="Compute full output hashes; use separately from memory runs"
+ )
+ parser.add_argument("--worker", action="store_true", help=argparse.SUPPRESS)
+ args = parser.parse_args()
+ if args.warmup < 0 or args.rounds < 1 or args.interval <= 0 or args.window_size < 1:
+ parser.error("warmup >= 0; rounds, interval and window-size must be positive")
+ args.repo = args.repo.resolve()
+ args.output = args.output.resolve()
+ args.pdf = [path.resolve() for path in args.pdf]
+ if not (args.repo / "mineru" / "parser").is_dir() or not all(path.is_file() for path in args.pdf):
+ parser.error("repo must contain mineru/parser and every PDF must exist")
+ return args
+
+
+def _fingerprint(document: Any) -> str:
+ """包含完整素材计算共享协议摘要,不使用会省略 PDF 图片的产品封装。"""
+ value = document.to_dict(skip_defaults=False)
+ payload = json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode()
+ return hashlib.sha256(payload).hexdigest()
+
+
+def _worker(args: argparse.Namespace) -> None:
+ """在指定 checkout 解析真实文件,每轮释放结果且不额外触发垃圾回收。"""
+ sys.path.insert(0, str(args.repo))
+ from mineru.parser.mineru_parser import MinerUParser
+ from mineru.backend.analysis.pdf.images import shutdown_pdf_render_executor
+
+ parser = MinerUParser(tier=args.tier, parse_mode=args.mode)
+ try:
+ with (args.output / "rounds.jsonl").open("w", encoding="utf-8") as stream:
+ for index in range(args.warmup + args.rounds):
+ path = args.pdf[index % len(args.pdf)]
+ started = time.monotonic()
+ result = parser.parse(path)
+ parsed = time.monotonic()
+ record = {
+ "index": index,
+ "warmup": index < args.warmup,
+ "pdf": str(path),
+ "started": started,
+ "parse_seconds": parsed - started,
+ "pages": len(result.pages),
+ }
+ if args.fingerprints:
+ record["middle_sha256"] = _fingerprint(result.middle_json)
+ record["model_sha256"] = _fingerprint(result._model_output)
+ del result
+ record["released"] = time.monotonic()
+ stream.write(json.dumps(record) + "\n")
+ stream.flush()
+ finally:
+ shutdown_pdf_render_executor()
+
+
+def _sample_processes(root: Any) -> list[dict[str, Any]]:
+ """分别采样解析进程与所有子进程,权限不足的 USS 保留为空而非零。"""
+ import psutil
+
+ records = []
+ try:
+ processes = [root, *root.children(recursive=True)]
+ except psutil.NoSuchProcess:
+ return records
+ for process in processes:
+ try:
+ rss = process.memory_info().rss
+ try:
+ uss = getattr(process.memory_full_info(), "uss", None)
+ except (psutil.AccessDenied, psutil.NoSuchProcess):
+ uss = None
+ records.append(
+ {
+ "pid": process.pid,
+ "role": "parser" if process.pid == root.pid else "child",
+ "rss": rss,
+ "uss": uss,
+ }
+ )
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ continue
+ return records
+
+
+def _summarize(args: argparse.Namespace, exit_code: int) -> dict[str, Any]:
+ """汇总测量阶段耗时和各 PID 峰值,保留原始采样用于窗口及轮次对齐。"""
+ rounds_path = args.output / "rounds.jsonl"
+ rounds = [json.loads(line) for line in rounds_path.read_text().splitlines()] if rounds_path.exists() else []
+ measured = [record for record in rounds if not record["warmup"]]
+ peaks: dict[int, dict[str, Any]] = {}
+ total_rss_peak = 0
+ total_uss_peak: int | None = None
+ for line in (args.output / "samples.jsonl").read_text().splitlines():
+ sample = json.loads(line)
+ if not measured or not (measured[0]["started"] <= sample["time"] <= measured[-1]["released"]):
+ continue
+ total_rss_peak = max(total_rss_peak, sum(item["rss"] for item in sample["processes"]))
+ uss_values = [item["uss"] for item in sample["processes"]]
+ if uss_values and all(value is not None for value in uss_values):
+ total_uss_peak = max(total_uss_peak or 0, sum(uss_values))
+ for item in sample["processes"]:
+ peak = peaks.setdefault(item["pid"], {**item})
+ peak["rss"] = max(peak["rss"], item["rss"])
+ if item["uss"] is not None:
+ peak["uss"] = max(peak["uss"] or 0, item["uss"])
+ return {
+ "exit_code": exit_code,
+ "repo": str(args.repo),
+ "python": sys.version,
+ "platform": platform.platform(),
+ "libc": platform.libc_ver(),
+ "docvortex": importlib.metadata.version("docvortex"),
+ "trim": args.trim,
+ "tier": args.tier,
+ "mode": args.mode,
+ "window_size": args.window_size,
+ "fingerprints": args.fingerprints,
+ "measured_rounds": len(measured),
+ "median_parse_seconds": statistics.median(record["parse_seconds"] for record in measured) if measured else None,
+ "process_peaks": list(peaks.values()),
+ "sampled_total_rss_peak": total_rss_peak if peaks else None,
+ "sampled_total_uss_peak": total_uss_peak,
+ }
+
+
+def main() -> None:
+ """启动独立解析进程,保存逐轮摘要、外部采样和解析日志。"""
+ args = _arguments()
+ if args.worker:
+ _worker(args)
+ return
+ import psutil
+
+ # 禁止覆盖上一组实验,避免把不同 checkout 或开关的证据混在一起。
+ args.output.mkdir(parents=True, exist_ok=False)
+ environment = {
+ **os.environ,
+ "MINERU_MALLOC_TRIM": args.trim,
+ "MINERU_PROCESSING_WINDOW_SIZE": str(args.window_size),
+ }
+ # 子进程切换 cwd 后仍必须使用父进程已解析的绝对输入路径。
+ command = [
+ sys.executable,
+ str(Path(__file__).resolve()),
+ "--worker",
+ "--repo",
+ str(args.repo),
+ "--pdf",
+ *(str(path) for path in args.pdf),
+ "--output",
+ str(args.output),
+ "--tier",
+ args.tier,
+ "--mode",
+ args.mode,
+ "--trim",
+ args.trim,
+ "--warmup",
+ str(args.warmup),
+ "--rounds",
+ str(args.rounds),
+ "--window-size",
+ str(args.window_size),
+ ]
+ if args.fingerprints:
+ command.append("--fingerprints")
+ with (args.output / "parse.log").open("w") as log, (args.output / "samples.jsonl").open("w") as samples:
+ process = subprocess.Popen(command, env=environment, cwd=args.repo, stdout=log, stderr=subprocess.STDOUT)
+ root = psutil.Process(process.pid)
+ try:
+ while process.poll() is None:
+ samples.write(json.dumps({"time": time.monotonic(), "processes": _sample_processes(root)}) + "\n")
+ samples.flush()
+ time.sleep(args.interval)
+ exit_code = process.wait()
+ finally:
+ if process.poll() is None:
+ process.terminate()
+ process.wait()
+ summary = _summarize(args, exit_code)
+ (args.output / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n")
+ print(json.dumps(summary, ensure_ascii=False, indent=2))
+ if exit_code:
+ raise SystemExit(exit_code)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/unittest/test_pdf_memory_benchmark.py b/tests/unittest/test_pdf_memory_benchmark.py
new file mode 100644
index 00000000..53296f6b
--- /dev/null
+++ b/tests/unittest/test_pdf_memory_benchmark.py
@@ -0,0 +1,54 @@
+"""守卫外部内存采样的预热排除、同时刻合计和未知 USS 语义。"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+
+from scripts import benchmark_pdf_memory
+
+
+def test_benchmark_reports_simultaneous_peaks_and_unknown_uss(tmp_path: Path) -> None:
+ """排除预热峰值,不能把不同时间的 PID 峰值相加或把未知 USS 当作零。"""
+ rounds = [
+ {"warmup": True, "started": 0, "released": 1, "parse_seconds": 50},
+ {"warmup": False, "started": 2, "released": 3, "parse_seconds": 1},
+ {"warmup": False, "started": 4, "released": 5, "parse_seconds": 3},
+ ]
+ samples = [
+ {"time": 0.5, "processes": [{"pid": 1, "role": "parser", "rss": 10000, "uss": 10000}]},
+ {
+ "time": 2.5,
+ "processes": [
+ {"pid": 1, "role": "parser", "rss": 100, "uss": 50},
+ {"pid": 2, "role": "child", "rss": 200, "uss": 150},
+ ],
+ },
+ {
+ "time": 4.5,
+ "processes": [
+ {"pid": 1, "role": "parser", "rss": 200, "uss": None},
+ {"pid": 2, "role": "child", "rss": 50, "uss": 30},
+ ],
+ },
+ ]
+ (tmp_path / "rounds.jsonl").write_text("\n".join(json.dumps(record) for record in rounds))
+ (tmp_path / "samples.jsonl").write_text("\n".join(json.dumps(record) for record in samples))
+ args = SimpleNamespace(
+ output=tmp_path, repo=tmp_path, trim="0", tier="flash", mode="txt", window_size=2, fingerprints=False
+ )
+ summary = benchmark_pdf_memory._summarize(args, 0)
+ assert summary["measured_rounds"] == 2
+ assert summary["median_parse_seconds"] == 2
+ assert summary["sampled_total_rss_peak"] == 300
+ assert summary["sampled_total_uss_peak"] == 200
+ assert [record["rss"] for record in summary["process_peaks"]] == [200, 200]
+
+ # 某个 PID 的 USS 始终不可读时,不生成不完整的总体 USS 峰值。
+ for sample in samples:
+ sample["processes"][0]["uss"] = None
+ (tmp_path / "samples.jsonl").write_text("\n".join(json.dumps(record) for record in samples))
+ summary = benchmark_pdf_memory._summarize(args, 0)
+ assert summary["sampled_total_uss_peak"] is None
+ assert summary["process_peaks"][0]["uss"] is None
diff --git a/tests/unittest/test_pdf_memory_lifecycle.py b/tests/unittest/test_pdf_memory_lifecycle.py
new file mode 100644
index 00000000..c680d7a5
--- /dev/null
+++ b/tests/unittest/test_pdf_memory_lifecycle.py
@@ -0,0 +1,226 @@
+"""验证窗口临时引用释放、结果素材保留和文档级回收顺序。"""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import weakref
+from io import BytesIO
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import Mock
+
+import numpy as np
+import pytest
+from PIL import Image
+
+from mineru.backend import analyze
+from mineru.backend.analysis.pdf import pipeline, window
+from mineru.model.runtime import memory
+
+
+def _window_probe(monkeypatch: pytest.MonkeyPatch, failure: str = "") -> SimpleNamespace:
+ """隔离推理模型,保留真实数组、表格裁图和素材编码以检查窗口边界。"""
+ probe = SimpleNamespace(arrays=[], crops=[], images=[], events=[])
+ original_collect = window._collect_table_items
+ original_attach = window._attach_visual_block_images
+
+ def fail_at(stage: str) -> None:
+ """在指定阶段抛出可辨识的业务异常。"""
+ if failure == stage:
+ raise RuntimeError(stage)
+
+ def render(**_options: Any) -> list[dict[str, Any]]:
+ """下一窗口分配图片之前,检查上一窗口图像数组与表格视图已释放。"""
+ assert all(ref() is None for ref in probe.arrays + probe.crops)
+ fail_at("render")
+ image = Image.new("RGB", (40, 40), "red")
+ probe.images.append(image)
+ probe.events.append("render")
+ return [{"img_pil": image, "scale": 1}]
+
+ def layout(_images: list[Image.Image], *, batch_size: int) -> list[list[dict[str, Any]]]:
+ """返回可由真实表格裁图函数处理的像素坐标。"""
+ assert batch_size > 0
+ fail_at("layout")
+ return [[{"label": "table", "bbox": [0, 0, 20, 20]}]]
+
+ def collect(layouts: list[list[dict[str, Any]]], arrays: list[np.ndarray]) -> list[dict[str, Any]]:
+ """只用弱引用观察独立页图数组及由真实函数产生的表格裁图。"""
+ probe.arrays.extend(weakref.ref(array) for array in arrays)
+ items = original_collect(layouts, arrays)
+ probe.crops.extend(weakref.ref(item["table_img"]) for item in items)
+ return items
+
+ def blocks(*_args: Any, **_kwargs: Any) -> list[list[dict[str, Any]]]:
+ """生成最小视觉块,供真实 JPEG 编码和公共协议转换消费。"""
+ return [[{"type": "image", "bbox": [0.0, 0.0, 1.0, 1.0], "content": ""}]]
+
+ def orient(*_args: Any) -> None:
+ """模拟表格方向推理的异常边界。"""
+ fail_at("orientation")
+
+ def text(*args: Any) -> list[list[dict[str, Any]]]:
+ """保持已有块与素材归属,模拟 OCR 异常。"""
+ fail_at("ocr")
+ return args[2]
+
+ def vlm(**_kwargs: Any) -> list[list[dict[str, Any]]]:
+ """模拟 VLM 推理成功或失败,但不持有传入页图。"""
+ fail_at("vlm")
+ return blocks()
+
+ def attach(*args: Any, **kwargs: Any) -> None:
+ """真实编码独立 JPEG 素材,然后覆盖裁图阶段异常。"""
+ original_attach(*args, **kwargs)
+ fail_at("crop")
+
+ def trimmed() -> bool:
+ """正常窗口回收前必须已释放临时数组,异常时只检查容器清理。"""
+ if not failure:
+ assert all(ref() is None for ref in probe.arrays + probe.crops)
+ probe.events.append("trim")
+ return False
+
+ monkeypatch.setattr(window, "_configured_window_size", lambda default: 1)
+ monkeypatch.setattr(window, "_get_window_pdf_pages", lambda *_args: [object()])
+ monkeypatch.setattr(window, "load_images_from_pdf_bytes_range", render)
+ monkeypatch.setattr(window, "_collect_table_items", collect)
+ monkeypatch.setattr(window, "_apply_table_orientations", orient)
+ monkeypatch.setattr(window, "_build_vl_style_layout_blocks", blocks)
+ monkeypatch.setattr(window, "_process_text_and_formulas", text)
+ monkeypatch.setattr(window, "_process_flash_ocr", text)
+ monkeypatch.setattr(window, "_apply_seal_ocr", lambda *_args: None)
+ monkeypatch.setattr(window, "_convert_vlm_results_to_model_list", lambda value: value)
+ monkeypatch.setattr(window, "_attach_visual_block_images", attach)
+ monkeypatch.setattr(window, "trim_process_heap", trimmed)
+ probe.model = SimpleNamespace(device="cpu", layout_model=SimpleNamespace(batch_predict=layout))
+ probe.predictor = SimpleNamespace(batch_extract_with_layout=vlm)
+ return probe
+
+
+def _run_windows(probe: SimpleNamespace, *, effort: str = "medium", pages: int = 2) -> list[list[dict[str, Any]]]:
+ """通过真实窗口入口分析模拟页面,不初始化任何神经模型。"""
+ document = SimpleNamespace(page_count=pages)
+ return window.process_pdf_windows(
+ b"pdf",
+ document,
+ effort=effort,
+ parse_mode="ocr",
+ image_analysis=True,
+ flash_txt_mode=False,
+ hybrid_model=probe.model,
+ vlm_predictor=probe.predictor,
+ )
+
+
[email protected]("effort", ["flash", "medium", "high"])
+def test_previous_window_arrays_die_before_next_render(monkeypatch: pytest.MonkeyPatch, effort: str) -> None:
+ """跨窗口释放完整数组与裁图,输出中的真实 JPEG 数据仍完整可读。"""
+ probe = _window_probe(monkeypatch)
+ result = _run_windows(probe, effort=effort)
+ assert probe.events == ["render", "trim", "render", "trim"]
+ assert len(probe.arrays) == len(probe.crops) == 2
+ assert len(result) == 2
+ for page in result:
+ with Image.open(BytesIO(base64.b64decode(page[0]["image_base64"].split(",", 1)[1]))) as image:
+ assert image.size == (40, 40)
+ for image in probe.images:
+ with pytest.raises(ValueError, match="closed image"):
+ image.getpixel((0, 0))
+
+
[email protected]("failure", ["render", "layout", "orientation", "ocr", "vlm", "crop"])
+def test_window_failure_closes_images_and_clears_owned_containers(monkeypatch: pytest.MonkeyPatch, failure: str) -> None:
+ """异常栈保留时也清空本层图像容器,并在每种失败路径尝试外层回收。"""
+ probe = _window_probe(monkeypatch, failure)
+ with pytest.raises(RuntimeError, match=failure) as caught:
+ _run_windows(probe, effort="high" if failure == "vlm" else "medium")
+ assert probe.events[-1] == "trim"
+ for image in probe.images:
+ with pytest.raises(ValueError, match="closed image"):
+ image.getpixel((0, 0))
+ for entry in caught.traceback:
+ if entry.name == "_process_pdf_window":
+ for name in ("images_list", "images_pil_list", "np_images", "table_items"):
+ assert entry.frame.f_locals[name] == []
+
+
[email protected]("native", [False, True])
[email protected]("failure", ["", "analysis", "close", "device"])
[email protected]("enabled", [False, True])
+def test_document_cleanup_order_and_global_switch(
+ monkeypatch: pytest.MonkeyPatch, native: bool, failure: str, enabled: bool
+) -> None:
+ """正常和异常路径均按文档、设备、CPU 堆顺序清理,Flash 原生不走设备清理。"""
+ events: list[str] = []
+
+ def stage(name: str) -> None:
+ """记录阶段并注入所选错误,检查后续清理仍然执行。"""
+ events.append(name)
+ if failure == name:
+ raise RuntimeError(name)
+
+ def process(*_args: Any, **_kwargs: Any) -> list[Any]:
+ """返回空文档以独立检查生命周期,不涉及协议内容。"""
+ stage("analysis")
+ return []
+
+ def trim(_pad: int) -> int:
+ """记录真实开关控制后的底层回收调用。"""
+ events.append("trim")
+ return 1
+
+ monkeypatch.setenv("MINERU_MALLOC_TRIM", "1" if enabled else "0")
+ monkeypatch.setattr(memory, "sys", SimpleNamespace(platform="linux"))
+ monkeypatch.setattr(memory, "_get_malloc_trim", lambda: trim)
+ monkeypatch.setattr(pipeline, "PDFDocument", lambda _data: SimpleNamespace(close=lambda: stage("close")))
+ monkeypatch.setattr(pipeline, "process_pdf_windows", process)
+ monkeypatch.setattr(pipeline, "clean_memory", lambda _device: stage("device"))
+ monkeypatch.setattr(
+ pipeline,
+ "HybridLocalModelContextSingleton",
+ lambda: SimpleNamespace(get_model=lambda: SimpleNamespace(device="cpu")),
+ )
+ if failure and not (native and failure == "device"):
+ with pytest.raises(RuntimeError, match=failure):
+ pipeline.analyze_pdf(b"pdf", effort="flash", parse_mode="txt" if native else "ocr")
+ else:
+ pipeline.analyze_pdf(b"pdf", effort="flash", parse_mode="txt" if native else "ocr")
+ assert events == ["analysis", "close"] + ([] if native else ["device"]) + (["trim"] if enabled else [])
+
+
[email protected]("enabled", [False, True])
[email protected]("asynchronous", [False, True])
+def test_real_window_and_document_hooks_share_switch(
+ monkeypatch: pytest.MonkeyPatch, enabled: bool, asynchronous: bool
+) -> None:
+ """同步和异步公共入口的两个窗口与文档回收均受唯一开关控制。"""
+ probe = _window_probe(monkeypatch)
+ monkeypatch.setattr(window, "trim_process_heap", memory.trim_process_heap)
+ monkeypatch.setenv("MINERU_MALLOC_TRIM", "1" if enabled else "0")
+ monkeypatch.setattr(memory, "sys", SimpleNamespace(platform="linux"))
+ malloc_trim = Mock(return_value=1)
+ monkeypatch.setattr(memory, "_get_malloc_trim", lambda: malloc_trim)
+ document = Mock(page_count=2, close=Mock())
+ monkeypatch.setattr(window, "_get_window_pdf_pages", lambda *_args: [object()])
+ monkeypatch.setattr(pipeline, "PDFDocument", lambda _data: document)
+ monkeypatch.setattr(pipeline, "HybridLocalModelContextSingleton", lambda: SimpleNamespace(get_model=lambda: probe.model))
+ monkeypatch.setattr(pipeline, "clean_memory", lambda _device: None)
+ if asynchronous:
+ middle, model = asyncio.run(analyze.aio_doc_analyze(b"pdf", effort="medium", parse_mode="ocr"))
+ else:
+ middle, model = analyze.doc_analyze(b"pdf", effort="medium", parse_mode="ocr")
+ assert len(middle.pages) == len(model.pages) == 2
+ assert malloc_trim.call_count == (3 if enabled else 0)
+
+
+def test_allocator_failure_preserves_window_exception(monkeypatch: pytest.MonkeyPatch) -> None:
+ """真实回收工具吞掉 allocator 故障,外层仍收到原始推理异常。"""
+ probe = _window_probe(monkeypatch, "ocr")
+ monkeypatch.setattr(window, "trim_process_heap", memory.trim_process_heap)
+ monkeypatch.setenv("MINERU_MALLOC_TRIM", "1")
+ monkeypatch.setattr(memory, "sys", SimpleNamespace(platform="linux"))
+ monkeypatch.setattr(memory, "_get_malloc_trim", lambda: Mock(side_effect=RuntimeError("allocator")))
+ with pytest.raises(RuntimeError, match="^ocr$"):
+ _run_windows(probe)
diff --git a/tests/unittest/test_process_heap_memory.py b/tests/unittest/test_process_heap_memory.py
new file mode 100644
index 00000000..c3fc57eb
--- /dev/null
+++ b/tests/unittest/test_process_heap_memory.py
@@ -0,0 +1,104 @@
+"""覆盖可选 CPU 堆回收的能力检测、缓存、开关与故障隔离。"""
+
+from __future__ import annotations
+
+import ctypes
+import os
+import subprocess
+import sys
+from collections.abc import Iterator
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+
+from mineru.model.runtime import memory
+
+
[email protected](autouse=True)
+def isolate_allocator(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
+ """隔离每个用例的 libc 缓存与平台,确保不会调用真实系统分配器。"""
+ memory._get_malloc_trim.cache_clear()
+ monkeypatch.delenv("MINERU_MALLOC_TRIM", raising=False)
+ monkeypatch.setattr(memory, "sys", SimpleNamespace(platform="linux"))
+ yield
+ memory._get_malloc_trim.cache_clear()
+
+
[email protected]("value", [None, "", "0", "false", "no", "off", "disabled", "invalid", "2"])
+def test_disabled_trim_does_not_load_allocator(monkeypatch: pytest.MonkeyPatch, value: str | None) -> None:
+ """默认关闭及非法配置不得探测 libc,更不能调用设备清理或垃圾回收。"""
+ if value is not None:
+ monkeypatch.setenv("MINERU_MALLOC_TRIM", value)
+ load = Mock(side_effect=AssertionError("must not load libc"))
+ monkeypatch.setattr(ctypes, "CDLL", load)
+ monkeypatch.setattr(memory.gc, "collect", Mock(side_effect=AssertionError("must not collect")))
+ monkeypatch.setattr(memory, "_optional_torch", Mock(side_effect=AssertionError("must not load torch")))
+ assert memory.trim_process_heap() is False
+ load.assert_not_called()
+
+
[email protected]("value", ["1", "true", "YES", " On "])
[email protected]("released", [0, 1])
+def test_enabled_trim_caches_signature_but_not_switch(monkeypatch: pytest.MonkeyPatch, value: str, released: int) -> None:
+ """只缓存正确 ABI 的底层函数,每次调用仍检查开关并报告实际回收结果。"""
+ malloc_trim = Mock(return_value=released)
+ load = Mock(return_value=SimpleNamespace(malloc_trim=malloc_trim))
+ monkeypatch.setattr(ctypes, "CDLL", load)
+ monkeypatch.setenv("MINERU_MALLOC_TRIM", value)
+ assert memory.trim_process_heap() is bool(released)
+ assert memory.trim_process_heap() is bool(released)
+ load.assert_called_once_with(None)
+ assert malloc_trim.argtypes == [ctypes.c_size_t]
+ assert malloc_trim.restype is ctypes.c_int
+ assert malloc_trim.call_count == 2
+ malloc_trim.assert_called_with(0)
+ monkeypatch.setenv("MINERU_MALLOC_TRIM", "0")
+ assert memory.trim_process_heap() is False
+ assert malloc_trim.call_count == 2
+
+
[email protected]("platform", ["darwin", "win32"])
+def test_unsupported_platform_does_not_load_libc(monkeypatch: pytest.MonkeyPatch, platform: str) -> None:
+ """显式开启也不会在不支持的平台加载 libc。"""
+ monkeypatch.setenv("MINERU_MALLOC_TRIM", "1")
+ monkeypatch.setattr(memory, "sys", SimpleNamespace(platform=platform))
+ load = Mock(side_effect=AssertionError("must not load libc"))
+ monkeypatch.setattr(ctypes, "CDLL", load)
+ assert memory.trim_process_heap() is False
+ load.assert_not_called()
+
+
[email protected]("failure", ["load", "symbol", "call"])
+def test_allocator_failures_are_optional(monkeypatch: pytest.MonkeyPatch, failure: str) -> None:
+ """libc 加载、符号缺失和底层调用失败都返回空操作结果。"""
+ monkeypatch.setenv("MINERU_MALLOC_TRIM", "1")
+ library = SimpleNamespace()
+ if failure == "call":
+ library.malloc_trim = Mock(side_effect=RuntimeError("allocator failed"))
+ load = Mock(side_effect=OSError("no libc")) if failure == "load" else Mock(return_value=library)
+ monkeypatch.setattr(ctypes, "CDLL", load)
+ assert memory.trim_process_heap() is False
+ assert memory.trim_process_heap() is False
+ load.assert_called_once_with(None)
+
+
+def test_trim_import_and_call_do_not_load_torch() -> None:
+ """在干净解释器中验证导入无配置副作用,关闭的 CPU 回收不加载 Torch。"""
+ code = """
+import os
+import sys
+before = dict(os.environ)
+from mineru.model.runtime.memory import trim_process_heap
+assert dict(os.environ) == before
+assert trim_process_heap() is False
+assert 'torch' not in sys.modules
+"""
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ env={**os.environ, "MINERU_MALLOC_TRIM": "0"},
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ assert result.returncode == 0, result.stderr