Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
fix(webui): retire preparations without blocking native selections
myhloli28f248cd6417
diff --git a/mineru/kit/gradio/sources.py b/mineru/kit/gradio/sources.pyindex ac6d509f..1beb1e70 100644--- a/mineru/kit/gradio/sources.py+++ b/mineru/kit/gradio/sources.py@@ -95,7 +95,7 @@ class SessionSources:self.output_root = output_rootself.current: dict[str, tuple[str, _SourceLease]] = {}self.revisions: dict[str, int] = {}- self.cleanups: set[asyncio.Task[None]] = set()+ self.cleanups: dict[asyncio.Task[None], str] = {}async def prepare(self, session: str, path: Path, source_id: str, revision: int) -> PreparedSource:"""接收单调选择修订号,拒绝晚到准备请求并复用本轮已创建的任务。"""@@ -122,14 +122,14 @@ class SessionSources:return sourcefinally:if previous:- self._schedule_cleanup(previous[1])+ self._schedule_cleanup(session, previous[1])await self._cleanup(lease)- def _schedule_cleanup(self, lease: _SourceLease) -> None:- """旧同步准备在后台安全退出,不阻塞已经就绪的新文件回执。"""+ def _schedule_cleanup(self, session: str, lease: _SourceLease) -> None:+ """按会话登记后台回收,不阻塞新文件就绪,关闭时仍可等待自身任务。"""task = asyncio.create_task(self._cleanup(lease))- self.cleanups.add(task)- task.add_done_callback(self.cleanups.discard)+ self.cleanups[task] = session+ task.add_done_callback(self.cleanups.pop)async def acquire(self, session: str, path: Path, *, source_id: str = "") -> tuple[PreparedSource, _SourceLease]:"""浏览器使用预检记录;公开 API 在转换前走同一准备流程。"""@@ -161,7 +161,7 @@ class SessionSources:await self._cleanup(lease)async def retire(self, session: str, *, revision: int | None = None) -> None:- """清除时保留修订屏障,关闭会话时释放记录,并等待同步转换安全退出。"""+ """选择变更只失效并后台回收,关闭会话时等待自身旧任务安全退出。"""if revision is None:self.revisions.pop(session, None)else:@@ -171,7 +171,11 @@ class SessionSources:previous = self.current.pop(session, None)if previous:previous[1].retired = True- await self._cleanup(previous[1])+ self._schedule_cleanup(session, previous[1])+ if revision is None:+ for task, owner in tuple(self.cleanups.items()):+ if owner == session:+ await await_task_completion(task)async def _cleanup(self, lease: _SourceLease) -> None:"""等待同步准备真正结束后回收未引用目录,失败任务已自行清理。"""diff --git a/tests/unittest/test_kit_gradio_conversion.py b/tests/unittest/test_kit_gradio_conversion.pyindex 87884455..3e662b6b 100644--- a/tests/unittest/test_kit_gradio_conversion.py+++ b/tests/unittest/test_kit_gradio_conversion.py@@ -276,6 +276,63 @@ def test_local_selection_resets_results_before_upload_finishes(tmp_path: Path) -assert all(update == {"__type__": "update"} for update in preview(None, request, selected))[email protected]("extension", ["docx", "csv"])+def test_native_example_ready_does_not_wait_for_previous_preparation(tmp_path: Path, extension: str) -> None:+ """原生示例就绪不等待旧图片准备,关闭会话仍等待自身后台清理且不阻塞其他会话。"""+ from mineru.kit.gradio.sources import PreparedSource++ image = tmp_path / "previous.png"+ Image.new("RGB", (20, 30), "red").save(image)+ example = tmp_path / f"example.{extension}"+ example.write_bytes(b"native example")+ started, finish = threading.Event(), threading.Event()+ app = _application(tmp_path, SimpleNamespace())+ prepare = _callback(app, "prepare_uploaded_source")+ sources = inspect.getclosurevars(prepare).nonlocals["conversion_service"].sources+ original = sources.document_io.prepare_source+ request = SimpleNamespace(session_hash="native-example")++ def delayed(path: Path, *, source_id: str, output_root: Path) -> PreparedSource:+ """保持旧图片的同步准备未完成,以检测就绪回执和关闭回收的等待边界。"""+ started.set()+ assert finish.wait(10)+ return original(path, source_id=source_id, output_root=output_root)++ sources.document_io.prepare_source = delayed++ async def scenario() -> None:+ """通过真实上传和关闭回调交错请求,确认旧任务安全退出后才删除目录。"""+ first = json.dumps({"id": "a" * 32, "revision": 1, "path": str(image)})+ replacement = json.dumps({"id": "b" * 32, "revision": 2, "path": str(example)})+ old = asyncio.create_task(prepare(str(image), first, request))+ pending: list[asyncio.Task[Any]] = [old]+ try:+ assert await asyncio.to_thread(started.wait, 2)+ native = asyncio.create_task(prepare(str(example), replacement, request))+ pending.append(native)+ ready, _ = await asyncio.wait({native}, timeout=1)+ assert native in ready, "Native example is blocked by the old preparation"+ assert json.loads(native.result()) == {"id": "b" * 32, "path": str(example), "pdf": None, "error": ""}+ assert not old.done() and not finish.is_set()+ unrelated = asyncio.create_task(sources.retire("unrelated-session"))+ pending.append(unrelated)+ ready, _ = await asyncio.wait({unrelated}, timeout=1)+ assert unrelated in ready, "Another session is blocked by the old preparation"+ closing = asyncio.create_task(_callback(app, "unload_session")(request))+ pending.append(closing)+ await asyncio.sleep(0)+ assert not closing.done()+ finally:+ finish.set()+ await asyncio.gather(*pending, return_exceptions=True)+ assert "expired" in json.loads(old.result())["error"]+ closing.result()+ assert not (tmp_path / "output/gradio/sources" / ("a" * 32)).exists()+ assert request.session_hash not in sources.current and request.session_hash not in sources.revisions++ asyncio.run(scenario())++def test_conversion_and_poll_are_full_non_generator_responses(tmp_path: Path) -> None:"""通过 Gradio process_api 反复序列化,确认结果不会创建生成器差分缓存。"""from gradio import Request