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: resolve stale paths when locating files by sha256
jinzhenj28a2c8044e6f
diff --git a/mineru/doclib/server.py b/mineru/doclib/server.pyindex 419da259..558d0331 100644--- a/mineru/doclib/server.py+++ b/mineru/doclib/server.py@@ -68,6 +68,7 @@ from .rows import (WatchTargetRow,)from .services.parse_svc import (+ accessible_file_for_sha256,filter_pages_by_user_range,load_pages_from_done_batches,parse_image_sidecar_dir,@@ -1412,13 +1413,7 @@ class DoclibServer(AsyncDoclibInterface):async def _render_source_image_asset(self, plan: _ReadPlan, page: PageInfo) -> ContentAsset:if plan.target is None:raise InvalidRequestError("format_not_supported", "image format requires a page or block locator.", "format")- file_row = cast(- FileRow | None,- await self.state.db.fetchone(- "SELECT * FROM files WHERE sha256=? AND status=? LIMIT 1",- (plan.sha256, FILE_STATUS_ACTIVE),- ),- )+ file_row = await accessible_file_for_sha256(self.state.db, plan.sha256)if file_row is None:raise NotFoundError("no_accessible_file", "No active source file found for this document.", "locator")source_path = file_row["path"]diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.pyindex 151fa802..7ad89cae 100644--- a/mineru/doclib/services/parse_svc.py+++ b/mineru/doclib/services/parse_svc.py@@ -70,6 +70,26 @@ MAX_FTS_CHARS = 30_000FTS_HEAD_HALF = 15_000+async def accessible_file_for_sha256(db: DatabaseManager, sha256: str) -> FileRow | None:+ """Find the newest active file row whose path still exists.++ The same content (sha256) may be tracked at several paths; rows whose+ source file was moved away stay active until a refresh marks them+ deleted, so existence must be checked before trusting a path.+ """+ rows = cast(+ list[FileRow],+ await db.fetchall(+ "SELECT * FROM files WHERE sha256=? AND status=? ORDER BY updated_at DESC",+ (sha256, FILE_STATUS_ACTIVE),+ ),+ )+ for row in rows:+ if os.path.exists(row["path"]):+ return row+ return None++FileRefreshStatus = Literal["known", "new", "changed", "missing", "deleted", "unreachable", "unsupported", "error"]@@ -555,6 +575,9 @@ class ParseService:file_row = cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,)))if file_row:await self.fts.upsert_filename(file_row["id"], Path(path).stem, ext)+ # the source may have been moved here from another tracked path;+ # retire stale duplicates whose files no longer exist.+ await self._mark_moved_duplicate_files_deleted(sha256, path)return file_row# brand new document@@ -889,6 +912,22 @@ class ParseService:await self._record_count("parse_task.started.count", dimensions={"tier": task["tier"]})return task+ async def _mark_moved_duplicate_files_deleted(self, sha256: str, keep_path: str) -> None:+ rows = cast(+ list[FileRow],+ await self.db.fetchall(+ "SELECT id, path FROM files WHERE sha256=? AND status=? AND path<>?",+ (sha256, FILE_STATUS_ACTIVE, keep_path),+ ),+ )+ now = _now_ms()+ for row in rows:+ if not os.path.exists(row["path"]):+ await self.db.execute(+ "UPDATE files SET status=?, deleted_at=?, updated_at=? WHERE id=?",+ (FILE_STATUS_DELETED, now, now, row["id"]),+ )+async def process_doc(self, task: ParseRow) -> bool:"""Execute parse for a batch. Returns True on success."""task_start_ms = _now_ms()@@ -903,13 +942,7 @@ class ParseService:return False# find the file- file_row = cast(- FileRow | None,- await self.db.fetchone(- "SELECT * FROM files WHERE sha256=? AND status=? LIMIT 1",- (sha256, FILE_STATUS_ACTIVE),- ),- )+ file_row = await accessible_file_for_sha256(self.db, sha256)if file_row is None:await self._fail_task(task["id"], "no_accessible_file", "No active file found for this document")await self._record_parse_task_finished(@@ -1405,16 +1438,19 @@ class ParseService:)async def _rebuild_fts_after_invalidate(self, sha256: str) -> None:+ # FTS rebuild reads only cached parse batches, so any active row works;+ # keep it deterministic and tolerate rows whose file moved away.file_row = cast(FileRow | None,await self.db.fetchone(- "SELECT * FROM files WHERE sha256=? AND status=? LIMIT 1",+ "SELECT * FROM files WHERE sha256=? AND status=? ORDER BY updated_at DESC",(sha256, FILE_STATUS_ACTIVE),),)if file_row is None:await self.fts.delete(sha256)return+ doc_row = cast(DocRow | None, await self.db.fetchone("SELECT title, author FROM docs WHERE sha256=?", (sha256,)))rows = cast(list[ParseRow],@@ -1451,8 +1487,8 @@ class ParseService:sha256=sha256,tier=tier,text=text,- title=file_row.get("title") or "",- author=file_row.get("author") or "",+ title=(doc_row or {}).get("title") or "",+ author=(doc_row or {}).get("author") or "",)returndiff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.pyindex 92221efb..0b96f76c 100644--- a/tests/unittest/test_doclib_cache_semantics.py+++ b/tests/unittest/test_doclib_cache_semantics.py@@ -210,6 +210,11 @@ class _FakeDB:return Noneasync def fetchall(self, sql: str, params: tuple[Any, ...]) -> list[dict[str, Any]]:+ if sql.startswith("SELECT * FROM files WHERE sha256=? AND status=? ORDER BY updated_at DESC"):+ sha256 = params[0]+ if self.file_row and self.file_row.get("sha256") == sha256 and self.file_row["status"] == "active":+ return [self.file_row]+ return []if sql.startswith("SELECT * FROM parses WHERE id IN"):ids = set(params)return [row for row in self.parses if row["id"] in ids]@@ -1427,6 +1432,87 @@ def test_ingest_binds_file_sha_before_creating_parse_task(tmp_path: Path, monkeyasyncio.run(_run())+def test_ingest_moved_file_retargets_to_new_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ class _NoRulesConfig:+ async def match_rules(self, path: str, rule_type: str) -> list[dict[str, Any]]:+ return []++ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ service = ParseService(+ db=db,+ fts=_FilenameOnlyFTS(),+ config_svc=_NoRulesConfig(),+ data_dir=str(tmp_path / "data"),+ parse_lock_timeout_sec=1800,+ )++ async def _metadata(path: str) -> dict[str, Any]:+ return {+ "page_count": 1,+ "title": None,+ "author": None,+ "subject": None,+ "keywords": None,+ "is_image_based": 0,+ }++ monkeypatch.setattr(parse_svc_module, "extract_metadata", _metadata)++ old_dir = tmp_path / "old"+ new_dir = tmp_path / "new"+ old_dir.mkdir()+ new_dir.mkdir()+ source = old_dir / "doc.pdf"+ source.write_bytes(b"%PDF-1.4\n")+ first_row = await service.ingest_file(str(source))++ source.rename(new_dir / "doc.pdf")+ second_row = await service.ingest_file(str(new_dir / "doc.pdf"))++ assert first_row is not None+ assert second_row is not None+ assert second_row["path"] == str(new_dir / "doc.pdf")+ stale = await db.fetchone("SELECT status FROM files WHERE id=?", (first_row["id"],))+ assert stale["status"] == "deleted"+ accessible = await parse_svc_module.accessible_file_for_sha256(db, second_row["sha256"])+ assert accessible is not None+ assert accessible["path"] == str(new_dir / "doc.pdf")++ asyncio.run(_run())+++def test_accessible_file_for_sha256_skips_missing_paths(tmp_path: Path) -> None:+ sha256 = "e" * 64+ existing = tmp_path / "kept.pdf"+ existing.write_bytes(b"%PDF-1.4\n")+ missing = tmp_path / "moved.pdf"++ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ await db.execute(+ "INSERT INTO docs (sha256, short_id, size_bytes, first_seen_at, updated_at) VALUES (?, ?, ?, ?, ?)",+ (sha256, "sh0rt1d", 10, 1000, 1000),+ )+ insert_sql = (+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, watch_id, first_seen_at, updated_at) "+ "VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?)"+ )+ await db.execute(insert_sql, (str(missing), "moved.pdf", "pdf", 10, 10, sha256, 2000, 2000))+ await db.execute(insert_sql, (str(existing), "kept.pdf", "pdf", 10, 10, sha256, 1000, 1000))++ row = await parse_svc_module.accessible_file_for_sha256(db, sha256)+ assert row is not None+ assert row["path"] == str(existing)++ existing.unlink()+ assert await parse_svc_module.accessible_file_for_sha256(db, sha256) is None++ asyncio.run(_run())++def test_request_parse_explicit_image_ingests_and_queues_parse(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:class _NoRulesConfig:async def match_rules(self, path: str, rule_type: str) -> list[dict[str, Any]]:@@ -1813,34 +1899,34 @@ def test_request_parse_rejects_unsupported_file_type_before_parse_response(tmp_p@pytest.mark.parametrize(- ("ext", "target_ext"),- [- ("doc", "docx"),- ("ppt", "pptx"),- ("xls", "xlsx"),- ],+ "ext",+ ["doc", "ppt", "xls"],)-def test_request_parse_rejects_legacy_office_with_conversion_hint(tmp_path: Path, ext: str, target_ext: str) -> None:+def test_request_parse_accepts_legacy_office_formats(tmp_path: Path, ext: str) -> None:+ """legacy Office 二进制格式端到端可解析:request_parse 应接受并按 flash tier 排队。"""++ class _NoRulesConfig:+ async def match_rules(self, path: str, rule_type: str) -> list[dict[str, Any]]:+ return []+async def _run() -> None:db = DatabaseManager(str(tmp_path / "doclib.db"))await db.initialize()service = ParseService(db=db,fts=FTSManager(db),- config_svc=None,+ config_svc=_NoRulesConfig(),data_dir=str(tmp_path / "data"),parse_lock_timeout_sec=1800,)source = tmp_path / f"sample.{ext}"source.write_bytes(b"office")- with pytest.raises(InvalidRequestError) as exc_info:- await service.request_parse(str(source), tier="flash")+ response = await service.request_parse(str(source), tier="flash")- assert exc_info.value.code == "file_type_unsupported"- assert exc_info.value.param == "path"- assert f".{ext} files are not supported" in exc_info.value.message- assert f".{target_ext}" in exc_info.value.message+ assert response.tier == "flash"+ assert response.status == "pending"+ assert response.created_parse_ids or response.reused_parse_idsasyncio.run(_run())@@ -4289,10 +4375,12 @@ def test_process_doc_rejects_existing_office_temp_lock_file_task(tmp_path: Path)"updated_at": 123,}]+ lock_file = tmp_path / "~$package-size.xlsx"+ lock_file.write_bytes(b"")db = _FakeDB(parses=parses,file_row={- "path": "/tmp/~$package-size.xlsx",+ "path": str(lock_file),"sha256": sha256,"status": "active","filename": "~$package-size.xlsx",@@ -4335,10 +4423,12 @@ def test_process_doc_marks_empty_page_result_failed(tmp_path: Path) -> None:"updated_at": 123,}]+ source = tmp_path / "doc.pdf"+ source.write_bytes(b"%PDF-1.4\n")db = _FakeDB(parses=parses,file_row={- "path": "/tmp/doc.pdf",+ "path": str(source),"sha256": sha256,"status": "active","filename": "doc.pdf",@@ -4390,10 +4480,12 @@ def test_process_doc_preserves_remote_api_error_code(tmp_path: Path) -> None:"updated_at": 123,}]+ source = tmp_path / "doc.pdf"+ source.write_bytes(b"%PDF-1.4\n")db = _FakeDB(parses=parses,file_row={- "path": "/tmp/doc.pdf",+ "path": str(source),"sha256": sha256,"status": "active","filename": "doc.pdf",@@ -4561,10 +4653,12 @@ def test_process_doc_fails_when_batch_json_cannot_be_written(tmp_path: Path) ->"updated_at": 123,}]+ source = tmp_path / "doc.pdf"+ source.write_bytes(b"%PDF-1.4\n")db = _FakeDB(parses=parses,file_row={- "path": "/tmp/doc.pdf",+ "path": str(source),"sha256": sha256,"status": "active","filename": "doc.pdf",@@ -4623,10 +4717,12 @@ def test_process_doc_normalizes_full_document_range_from_actual_pages(tmp_path:}]doc_row = {"sha256": sha256, "short_id": "fffffff", "page_count": 10, "meta_tier": None}+ source = tmp_path / "book.epub"+ source.write_bytes(b"epub")db = _FakeDB(parses=parses,file_row={- "path": "/tmp/book.epub",+ "path": str(source),"ext": "epub","sha256": sha256,"status": "active",@@ -4690,10 +4786,12 @@ def test_process_doc_writes_cached_image_sidecars(tmp_path: Path) -> None:"updated_at": 123,}]+ source = tmp_path / "doc.pdf"+ source.write_bytes(b"%PDF-1.4\n")db = _FakeDB(parses=parses,file_row={- "path": "/tmp/doc.pdf",+ "path": str(source),"sha256": sha256,"status": "active","filename": "doc.pdf",diff --git a/tests/unittest/test_doclib_telemetry_core.py b/tests/unittest/test_doclib_telemetry_core.pyindex b1a5b833..2ca4935a 100644--- a/tests/unittest/test_doclib_telemetry_core.py+++ b/tests/unittest/test_doclib_telemetry_core.py@@ -375,6 +375,7 @@ def test_parse_service_process_doc_records_task_metrics(tmp_path) -> None:telemetry_svc=telemetry,)now = 1_700_000_000_000+ (tmp_path / "a.pdf").write_bytes(b"%PDF-1.4\n")await db.execute("INSERT INTO docs (sha256, short_id, size_bytes, file_type, page_count, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?)",@@ -445,6 +446,7 @@ def test_parse_service_requires_result_images_method(tmp_path) -> None:telemetry_svc=telemetry,)now = 1_700_000_000_000+ (tmp_path / "a.pdf").write_bytes(b"%PDF-1.4\n")await db.execute("INSERT INTO docs (sha256, short_id, size_bytes, file_type, page_count, first_seen_at, updated_at) ""VALUES (?, ?, ?, ?, ?, ?, ?)",