Skip to content

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

Fix doclib watch path normalization

jinzhenj1408bc0ef8f4
diff --git a/mineru/cli/path_utils.py b/mineru/cli/path_utils.py
index e3a2d510..d612885c 100644
--- a/mineru/cli/path_utils.py
+++ b/mineru/cli/path_utils.py
@@ -2,9 +2,9 @@
from __future__ import annotations
-import os
+from ..doclib.utils.path_utils import normalize_doclib_path
def normalize_cli_path(path: str) -> str:
"""Normalize a local filesystem path provided to the CLI."""
- return os.path.normpath(os.path.abspath(os.path.expanduser(path)))
+ return normalize_doclib_path(path)
diff --git a/mineru/doclib/background/watch.py b/mineru/doclib/background/watch.py
index 0b910e91..73baab57 100644
--- a/mineru/doclib/background/watch.py
+++ b/mineru/doclib/background/watch.py
@@ -15,6 +15,7 @@ from ..services.config_svc import ConfigService
from ..services.parse_svc import ParseService
from ..services.scan_svc import ScanService
from ..types import FILE_STATUS_ACTIVE, WATCH_STATUS_ACTIVE, WATCH_STATUS_UNREACHABLE
+from ..utils.path_utils import normalize_doclib_path, rebase_watch_event_path
logger = logging.getLogger("mineru.watch")
@@ -119,7 +120,7 @@ class WatchLoop:
if not self.running:
break
for _change_type, filepath in changes:
- await self._handle_event(filepath, watch_id)
+ await self._handle_event(filepath, watch_id, watch_root=path)
except Exception as exc:
logger.error(
"Watch loop failed for watch_id=%s path=%s: %s",
@@ -129,7 +130,12 @@ class WatchLoop:
exc_info=(type(exc), exc, exc.__traceback__),
)
- async def _handle_event(self, filepath: str, watch_id: int) -> None:
+ async def _handle_event(self, filepath: str, watch_id: int, *, watch_root: str | None = None) -> None:
+ filepath = (
+ rebase_watch_event_path(filepath, watch_root)
+ if watch_root is not None
+ else normalize_doclib_path(filepath)
+ )
ext = Path(filepath).suffix.lstrip(".").lower()
if ext not in DISCOVERABLE_EXTENSIONS or is_office_temp_lock_file(filepath):
return
diff --git a/mineru/doclib/services/cleanup_svc.py b/mineru/doclib/services/cleanup_svc.py
index 4d8f018b..8815c6d6 100644
--- a/mineru/doclib/services/cleanup_svc.py
+++ b/mineru/doclib/services/cleanup_svc.py
@@ -11,6 +11,7 @@ from ...errors import InvalidRequestError
from ..core.db import DatabaseManager
from ..rows import CountRow, DocRow, IdRow, WatchTargetRow
from ..types import FILE_STATUS_DELETED
+from ..utils.path_utils import normalize_doclib_path
FORGET_WATCH_ROOT_WARNING = "Path is a configured watch root and may be rediscovered on the next scan."
FORGET_UNDER_ACTIVE_WATCH_WARNING = "Path is under an active watch and may be rediscovered on the next scan."
@@ -199,7 +200,7 @@ def _days_ago_ms(days: int) -> int:
def _normalize_path(path: str) -> str:
- return os.path.normpath(os.path.abspath(os.path.expanduser(path.strip()))) if path.strip() else ""
+ return normalize_doclib_path(path)
def _path_prefix(path: str) -> str:
diff --git a/mineru/doclib/services/config_svc.py b/mineru/doclib/services/config_svc.py
index 4a9d89e3..57e8eadb 100644
--- a/mineru/doclib/services/config_svc.py
+++ b/mineru/doclib/services/config_svc.py
@@ -24,6 +24,7 @@ from ..types import (
RuleType,
WatchStatus,
)
+from ..utils.path_utils import normalize_doclib_path
class ConfigService:
@@ -86,6 +87,7 @@ class ConfigService:
async def add_watch(
self, path: str, removable: bool = False, label: str | None = None
) -> WatchTargetRow:
+ path = normalize_doclib_path(path)
if not os.path.isabs(path):
raise InvalidRequestError("invalid_request", f"Watch path must be absolute: {path}", "path")
if os.path.normpath(path) != path:
@@ -115,6 +117,7 @@ class ConfigService:
)
async def remove_watch(self, path: str) -> None:
+ path = normalize_doclib_path(path)
watch = cast(WatchTargetRow | None, await self.db.fetchone("SELECT * FROM watches WHERE path=?", (path,)))
if watch is None:
return
@@ -244,6 +247,7 @@ class ConfigService:
await self.db.execute("DELETE FROM parsing_rules WHERE id=?", (rule_id,))
async def match_rules(self, file_path: str, rule_type: RuleType) -> list[RuleRow]:
+ file_path = normalize_doclib_path(file_path)
rules = await self.list_rules(rule_type)
table = _rule_table(rule_type)
matched: list[RuleRow] = []
diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.py
index e67f57f7..233740ff 100644
--- a/mineru/doclib/services/parse_svc.py
+++ b/mineru/doclib/services/parse_svc.py
@@ -42,6 +42,7 @@ from ..types import (
FileInfo,
ParseResponse,
)
+from ..utils.path_utils import normalize_doclib_path
from .config_svc import ConfigService
logger = logging.getLogger("mineru.parse")
@@ -294,6 +295,7 @@ class ParseService:
This method owns file stat, DB row lookup, new/changed/known/missing/deleted
classification, and optional synchronous ingest.
"""
+ path = normalize_doclib_path(path)
ext = Path(path).suffix.lower().lstrip(".")
existing = cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,)))
if ext not in PARSEABLE_EXTENSIONS or (ext in IMAGE_EXTENSIONS and not allow_images) or is_office_temp_lock_file(path):
@@ -434,6 +436,7 @@ class ParseService:
async def ensure_ingested(self, path: str, watch_id: int | None = None, *, allow_images: bool = False) -> FileRow | None:
"""Synchronously discover and ingest a source path when needed."""
+ path = normalize_doclib_path(path)
refreshed = await self.refresh_file(path, watch_id=watch_id, ensure_ingested=True, allow_images=allow_images)
if refreshed.file is None or refreshed.status == "unsupported":
return None
@@ -448,6 +451,7 @@ class ParseService:
allow_images: bool = False,
) -> FileRow | None:
"""Ingest a discovered file: SHA-256 + metadata + trigger default parse."""
+ path = normalize_doclib_path(path)
start_ms = _now_ms()
status = "succeeded"
try:
@@ -465,6 +469,7 @@ class ParseService:
await self._record_duration("ingest.duration_bucket.count", start_ms, dimensions=dimensions)
async def _mark_file_error(self, path: str, error_code: str, error_msg: str) -> None:
+ path = normalize_doclib_path(path)
now = _now_ms()
await self.db.execute(
"UPDATE files SET sha256=NULL, locked_at=NULL, error_code=?, error_msg=?, updated_at=? WHERE path=?",
diff --git a/mineru/doclib/services/scan_svc.py b/mineru/doclib/services/scan_svc.py
index 0501d0dc..74f4c19f 100644
--- a/mineru/doclib/services/scan_svc.py
+++ b/mineru/doclib/services/scan_svc.py
@@ -29,6 +29,7 @@ from ..types import (
ScanStatus,
)
from ..core.db import DatabaseManager
+from ..utils.path_utils import normalize_doclib_path
from .config_svc import ConfigService
from .parse_svc import FileRefreshResult, ParseService
@@ -87,7 +88,7 @@ class ScanService:
source: ScanSource = SCAN_SOURCE_UNKNOWN,
watch_id: int | None = None,
) -> ScanInfo:
- normalized_path = os.path.abspath(os.path.expanduser(path))
+ normalized_path = normalize_doclib_path(path)
if kind == SCAN_KIND_WATCH:
watch = await self._resolve_watch(normalized_path, watch_id)
normalized_path = watch["path"]
@@ -254,7 +255,7 @@ class ScanService:
logger.warning("Failed to cleanup terminal scan logs: %s", exc)
async def _run_scan(self, task: ScanRow) -> "_ScanCounters":
- path = task["path"]
+ path = normalize_doclib_path(task["path"])
kind = task["kind"]
watch_id = task.get("watch_id")
counters = _ScanCounters()
diff --git a/mineru/doclib/utils/path_utils.py b/mineru/doclib/utils/path_utils.py
new file mode 100644
index 00000000..1a76aaf6
--- /dev/null
+++ b/mineru/doclib/utils/path_utils.py
@@ -0,0 +1,30 @@
+"""Path normalization helpers for doclib."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+
+def normalize_doclib_path(path: str) -> str:
+ """Normalize a user-facing doclib path without resolving symlinks."""
+ stripped = path.strip()
+ if not stripped:
+ return ""
+ return os.path.normpath(os.path.abspath(os.path.expanduser(stripped)))
+
+
+def rebase_watch_event_path(event_path: str, watch_root: str) -> str:
+ """Map a watcher event back into the stored watch-root namespace."""
+ normalized_event = normalize_doclib_path(event_path)
+ normalized_root = normalize_doclib_path(watch_root)
+ if not normalized_event or not normalized_root:
+ return normalized_event
+
+ event_real = Path(normalized_event).resolve(strict=False)
+ root_real = Path(normalized_root).resolve(strict=False)
+ try:
+ relative_event = event_real.relative_to(root_real)
+ except ValueError:
+ return normalized_event
+ return normalize_doclib_path(str(Path(normalized_root, relative_event)))
diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.py
index 3441005f..1e005c5c 100644
--- a/tests/unittest/test_doclib_cache_semantics.py
+++ b/tests/unittest/test_doclib_cache_semantics.py
@@ -1466,6 +1466,55 @@ def test_ensure_ingested_rebinds_changed_text_file_to_new_sha(tmp_path: Path) ->
asyncio.run(_run())
+def test_refresh_file_normalizes_lexical_path_aliases(tmp_path: Path) -> None:
+ async def _run() -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+ await db.initialize()
+ service = ParseService(
+ db=db, fts=FTSManager(db), config_svc=None, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
+ root = tmp_path / "docs"
+ root.mkdir()
+ source = root / "note.txt"
+ source.write_text("content", encoding="utf-8")
+ alias = root / "." / "nested" / ".." / "note.txt"
+
+ first = await service.refresh_file(str(alias))
+ second = await service.refresh_file(str(source))
+ rows = await db.fetchall("SELECT path FROM files ORDER BY id")
+
+ assert first.status == "new"
+ assert second.status == "known"
+ assert rows == [{"path": str(source)}]
+
+ asyncio.run(_run())
+
+
+def test_refresh_file_keeps_symlink_and_real_paths_as_distinct_file_entries(tmp_path: Path) -> None:
+ async def _run() -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+ await db.initialize()
+ service = ParseService(
+ db=db, fts=FTSManager(db), config_svc=None, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800
+ )
+ real_root = tmp_path / "real-root"
+ real_root.mkdir()
+ alias_root = tmp_path / "alias-root"
+ alias_root.symlink_to(real_root, target_is_directory=True)
+ source = real_root / "note.txt"
+ source.write_text("content", encoding="utf-8")
+
+ alias_result = await service.refresh_file(str(alias_root / "note.txt"))
+ real_result = await service.refresh_file(str(source))
+ rows = await db.fetchall("SELECT path FROM files ORDER BY path")
+
+ assert alias_result.status == "new"
+ assert real_result.status == "new"
+ assert rows == [{"path": str(alias_root / "note.txt")}, {"path": str(source)}]
+
+ asyncio.run(_run())
+
+
def test_refresh_file_marks_missing_known_path_deleted(tmp_path: Path) -> None:
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
@@ -2276,6 +2325,43 @@ def test_watch_event_ignores_image_files(tmp_path: Path) -> None:
asyncio.run(_run())
+def test_watch_event_rebases_realpath_alias_to_watch_root_namespace(tmp_path: Path) -> None:
+ async def _run() -> None:
+ class _ConfigService:
+ async def is_path_excluded(self, path: str) -> bool:
+ return False
+
+ class _ParseService:
+ def __init__(self) -> None:
+ self.refreshed: list[str] = []
+
+ async def refresh_file(self, filepath: str, watch_id: int) -> None:
+ self.refreshed.append(filepath)
+
+ real_root = tmp_path / "real-root"
+ real_root.mkdir()
+ alias_parent = tmp_path / "aliases"
+ alias_parent.mkdir()
+ alias_root = alias_parent / "watched"
+ alias_root.symlink_to(real_root, target_is_directory=True)
+ event_path = real_root / "a.txt"
+ event_path.write_text("content", encoding="utf-8")
+
+ parse_svc = _ParseService()
+ watch_loop = WatchLoop(
+ db=SimpleNamespace(),
+ config_svc=_ConfigService(),
+ parse_svc=parse_svc,
+ scan_interval_sec=300,
+ )
+
+ await watch_loop._handle_event(str(event_path), watch_id=1, watch_root=str(alias_root))
+
+ assert parse_svc.refreshed == [str(alias_root / "a.txt")]
+
+ asyncio.run(_run())
+
+
def test_scan_service_reuses_pending_scan_for_same_kind_and_path(tmp_path: Path) -> None:
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
diff --git a/tests/unittest/test_doclib_interface_contract.py b/tests/unittest/test_doclib_interface_contract.py
index e72139f4..9a0ecdd8 100644
--- a/tests/unittest/test_doclib_interface_contract.py
+++ b/tests/unittest/test_doclib_interface_contract.py
@@ -230,25 +230,19 @@ def test_add_watch_rejects_missing_directory(tmp_path) -> None:
asyncio.run(_run())
-def test_add_watch_rejects_non_absolute_or_unnormalized_path_with_structured_error(tmp_path) -> None:
+def test_add_watch_normalizes_user_path_before_storing(tmp_path) -> None:
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
service = ConfigService(db)
- with pytest.raises(InvalidRequestError) as relative_exc:
- await service.add_watch("relative/path")
- assert relative_exc.value.code == "invalid_request"
- assert relative_exc.value.param == "path"
-
root = tmp_path / "root"
root.mkdir()
unnormalized = str(root / ".." / root.name)
- with pytest.raises(InvalidRequestError) as normalized_exc:
- await service.add_watch(unnormalized)
- assert normalized_exc.value.code == "invalid_request"
- assert normalized_exc.value.param == "path"
+ watch = await service.add_watch(unnormalized)
+
+ assert watch["path"] == str(root)
asyncio.run(_run())