Skip to content

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

Align search results with file aliases

jinzhenj4b59960e9890
diff --git a/docs/next/architecture.md b/docs/next/architecture.md
index edb223eb..6c099133 100644
--- a/docs/next/architecture.md
+++ b/docs/next/architecture.md
@@ -241,7 +241,7 @@ watch 流程也调用同一发现/刷新步骤:
- watch file event、所有 scan 操作和上述 4 个同步 path 操作,都必须检查 path 当前是否存在。
- 如果 path 不存在,且所属 removable watch root 不可达,则标记为 `unreachable`。
- 如果 path 不存在,且不是设备整体不可达导致,则标记为 `deleted`,写入 `deleted_at`,保留 `sha256`。
-- 标记 `deleted` 或 `unreachable` 时不清理 FTS;find 默认只返回 active file,search 默认优先返回 active file paths,只有在已索引 doc 没有任何 active file 时才 fallback 返回非 active file paths。
+- 标记 `deleted` 或 `unreachable` 时不清理 FTS;find 默认只返回 active file。search JSON 返回全部 file aliases 及状态,非 JSON CLI 才使用 active 优先展示。
失败时按错误绑定对象写入对应层级:
@@ -328,7 +328,7 @@ doclib 不在 `parsed/` 中保存 Markdown、Content List 或 HTML。它们都
搜索策略:
- `fts_filenames` 用于文件名搜索。
-- `fts_contents` 用于内容搜索,同一文档只保留最高 tier 文本。
+- `fts_contents` 用于正文、标题和作者搜索,同一文档只保留最高 tier 内容,不存储或匹配 filename。
- 内容超过 30K 字符时,保留 head + tail,完整内容仍从解析产物读取。
- 中文分词采用 jieba + FTS5 `unicode61` 的组合方案。
diff --git a/docs/next/cli/mineru-library.md b/docs/next/cli/mineru-library.md
index 0382951e..2454a0b8 100644
--- a/docs/next/cli/mineru-library.md
+++ b/docs/next/cli/mineru-library.md
@@ -27,19 +27,23 @@ mineru search "keyword" --min-tier medium --type pdf
- 查询 `fts_contents`,未解析或未建立内容索引的文件不会命中正文检索。
- 按文档 SHA256 去重。
- 支持按 `file_type`、`tier`、`min_tier` 过滤。
-- 返回文件名、文件大小、页数、命中片段和 snippet 来源 tier。
-- 默认优先返回 active file paths;如果某个已索引 doc 没有任何 active file,则 fallback 返回非 active file paths。
+- 返回文档大小、页数、命中片段、snippet 来源 tier,以及关联的全部 file aliases。
+- JSON 返回全部 file aliases 及其状态,并按 file id 降序排列。
+- 非 JSON 输出存在 active files 时只展示 active paths;没有 active file 时展示全部 inactive paths。
+- 已索引的 orphan 文档仍可命中,非 JSON 输出提示文件已不存在。
- 通过 `--json` 提供结构化输出。
JSON 输出中的每条结果至少包含:
| 字段 | 说明 |
|------|------|
-| `filename` | 文件名,不含完整路径。 |
| `size_bytes` | 文件大小。 |
| `page_count` | 文档页数;未知时为 `null`。 |
| `snippet` | 命中的内容片段。 |
| `tier` | snippet 来源 tier。 |
+| `files` | 与文档 SHA 关联的全部 files,包含 `path`、`filename`、`ext`、`status`。 |
+
+`search` 不匹配 filename;按文件名定位使用 `mineru find`。
`search` 不应在 telemetry 中记录 query 或 snippet,但 CLI JSON 可以返回 snippet 供用户和 Agent 使用。
diff --git a/docs/next/decisions/0007-doclib-file-availability-lifecycle.md b/docs/next/decisions/0007-doclib-file-availability-lifecycle.md
index 5e48d79f..da4b261b 100644
--- a/docs/next/decisions/0007-doclib-file-availability-lifecycle.md
+++ b/docs/next/decisions/0007-doclib-file-availability-lifecycle.md
@@ -24,9 +24,9 @@ doclib 不只需要判断“同一路径内容是否变化”,还需要判断
| 状态 | 含义 | 默认 find | 默认 search | 是否保护 doc |
|------|------|-----------|----------------|--------------|
-| `active` | 路径当前存在且可访问 | 是 | 优先返回 | 是 |
-| `unreachable` | 所属 removable watch 当前不可达 | 否 | 无 active file 时 fallback 返回 | 是 |
-| `deleted` | 路径已确认不存在,且不是设备整体不可达导致 | 否 | 无 active file 时 fallback 返回 | 是 |
+| `active` | 路径当前存在且可访问 | 是 | JSON 返回;CLI 优先展示 | 是 |
+| `unreachable` | 所属 removable watch 当前不可达 | 否 | JSON 返回;CLI 无 active file 时展示 | 是 |
+| `deleted` | 路径已确认不存在,且不是设备整体不可达导致 | 否 | JSON 返回;CLI 无 active file 时展示 | 是 |
`deleted` file row 仍保留 `sha256`,并继续保护对应 doc。只有完全没有任何 file row 关联的 doc 才是 orphan。
@@ -119,7 +119,7 @@ FTS 生命周期跟随其对应主表记录:
- 标记 `deleted` 时不删除 `fts_filenames`。
- 标记 `unreachable` 时不删除 `fts_filenames`。
- 默认 `find` 只返回 active file。
-- 默认 `search` 优先返回 active file paths;如果某个已索引 doc 没有任何 active file,则 fallback 返回 non-active file paths。
+- `search` JSON 返回文档关联的全部 file aliases 及状态;非 JSON CLI 存在 active files 时只展示 active paths,否则展示全部 inactive paths。
### CLI 参数
@@ -144,7 +144,7 @@ FTS 生命周期跟随其对应主表记录:
### 方案 D: search 默认返回 unreachable / deleted
-部分拒绝。第一版默认 find 只返回当前可访问文件。search 则优先返回 active file paths;只有在某个已索引 doc 没有任何 active file 时,才 fallback 返回 unreachable / deleted paths,避免已索引历史文档完全不可定位。
+部分拒绝。第一版默认 find 只返回当前可访问文件。search JSON 返回全部 aliases,使调用方能看到 active、unreachable 和 deleted 状态;非 JSON CLI 使用 active 优先展示。完全没有 file row 的已索引文档仍作为 orphan 搜索结果返回。
## 影响
diff --git a/docs/next/everydoc-doclib-gap-review.md b/docs/next/everydoc-doclib-gap-review.md
index 54a394a8..97a7f477 100644
--- a/docs/next/everydoc-doclib-gap-review.md
+++ b/docs/next/everydoc-doclib-gap-review.md
@@ -52,7 +52,7 @@
- 删除/变更检测入口包括 watch event、watch scan,以及 4 个同步 source file path 操作: parse、info、docs?path、invalidate(path)。
- watch scan 采用两阶段刷新: 先 refresh DB 中该 watch 下的 active paths,再 `os.walk()` 发现当前文件系统中的新路径和变化路径。
- path 缺失且不属于设备整体不可达时,标记为 `deleted`,写入 `deleted_at`,保留 `sha256`,清空 `error_code` / `error_msg` / `locked_at`。
-- 默认 `find` 只返回 active file;默认 `search` 优先返回 active file paths,如果某个 doc 已有内容索引但没有任何 active file,则 fallback 返回非 active file paths。
+- 默认 `find` 只返回 active file;`search` JSON 返回全部 file aliases 及状态,非 JSON CLI 使用 active 优先展示。
- `PermissionError` 与其他 stat `OSError` 不表示删除,分别写入 `file_permission_denied` / `stat_failed`。
后续优化:
@@ -286,14 +286,14 @@ P0 结论:
- 如果 `tier` 与 `min_tier` 同时出现,二者同时生效;不兼容时返回空结果。
- 时间范围过滤、watch 过滤放到 P1。
- 搜索结果可信度不新增 `confidence` 或 `quality` 字段,只使用 `tier` 表达。
-- 搜索结果默认优先返回 active files;由于一个 doc SHA256 可对应多个 file rows,结果中的 `paths` 是所选 file rows 的路径列表。
-- 如果某个 doc 已有内容索引但没有任何 active file,则 fallback 返回非 active file paths,使 Agent 仍能定位 deleted / unreachable 的历史文档。
+- 搜索结果按 doc SHA256 聚合,结果中的 `files` 返回全部 file rows,包含 path、filename、ext 和 status,并按 file id 降序排列。
+- 非 JSON CLI 存在 active files 时只展示 active paths;否则展示全部 deleted / unreachable paths。没有 file row 的已索引文档仍作为 orphan 返回。
- `find()` 是文件名搜索,增加 `ext` 过滤;它仍默认只返回 active files。
后续优化:
- P1 再讨论 `mtime_after` / `mtime_before` / `watch_id`。
-- 如果未来 Agent 需要区分 fallback path 的状态,可在结果中增加结构化 file refs;P0 先保持 `paths` 列表。
+- Agent 通过结构化 `files` 区分 active、deleted 和 unreachable aliases。
### G-009 Agent citation 与更细粒度索引
diff --git a/docs/next/open-questions.md b/docs/next/open-questions.md
index f27b7367..c6d2b467 100644
--- a/docs/next/open-questions.md
+++ b/docs/next/open-questions.md
@@ -59,7 +59,7 @@
| Doc short id | `docs.short_id` 按 SHA256 7 位前缀起步、冲突递增长度、写入后保持稳定,详见 [ADR-0011](decisions/0011-doclib-doc-short-id.md)。 |
| Block locator | Agent-native 整体是 P0。P0 public locator 使用 1-based `page_no` / `block_no`,形态为 `doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}`,详见 [ADR-0012](decisions/0012-doclib-block-locator.md)。 |
| `mineru read` | 新增 locator-first 顶级读取命令;`parse` 和 `read` 共享 `ReadPlan` 与 `execute_read_plan()`,`read --format image` 进入 P0,详见 [ADR-0014](decisions/0014-mineru-read-command.md)。 |
-| `search/find/show file` JSON 输出 | `search` 输出文件名、文件大小、页数和 snippet;`find` 输出文件名、文件大小、页数;`show file` 输出文件大小、页数、文档 metadata 摘要、各 tier 已解析页和 active parse 摘要。 |
+| `search/find/show file` JSON 输出 | `search` 输出文档大小、页数、snippet 和完整 file aliases;`find` 输出文件名、文件大小、页数;`show file` 输出文件大小、页数、文档 metadata 摘要、各 tier 已解析页和 active parse 摘要。 |
| Tool SDK `server_url` | Tool SDK 的 PDF VLM / hybrid parser 可以保留 `server_url` 作为 parser-layer 高级 backend 参数;API-backed parser 使用 `api_url`。 |
| `MinerUApiParser` 位置 | API-backed parser 保持现状,公开入口继续使用 `from mineru.parser import MinerUApiParser`;不重命名,不移动到 `mineru.parser.remote`。 |
| `ParseResult` backend 字段 | `ParseResult` 不再持有 `_backend` / `_version_name`;backend 仅允许作为 page / middle-json 内部来源信息存在。 |
diff --git a/docs/next/sdk/doclib-client.md b/docs/next/sdk/doclib-client.md
index 58ccad85..97adecf3 100644
--- a/docs/next/sdk/doclib-client.md
+++ b/docs/next/sdk/doclib-client.md
@@ -144,11 +144,11 @@ def info(self, file_path: str) -> dict: ...
| 方法 | 响应 |
|------|------|
-| `search()` | `SearchResponse`,包含全文结果、snippet、paths、tier;支持 `file_type`、`tier`、`min_tier` 过滤。 |
+| `search()` | `SearchResponse`,包含全文结果、snippet、files、tier;支持 `file_type`、`tier`、`min_tier` 过滤。 |
| `find()` | `FindResponse`,包含文件名搜索结果;支持 `ext` 过滤。 |
| `get_file_by_path()` | `FileInfoResponse`,包含文件元信息、doc metadata 和 parse tiers。 |
-`search()` 的 `paths` 优先返回 active files;如果某个已索引 doc 没有任何 active file,则 fallback 返回非 active file paths。搜索结果可信度只通过 `tier` 表达。
+`search()` 的 `files` 返回与文档 SHA 关联的全部 file aliases,按 file id 降序排列;每项包含 path、filename、ext 和 status。已索引的 orphan 文档使用空列表。active 优先只属于非 JSON CLI 展示策略,不改变 SDK 响应。搜索结果可信度只通过 `tier` 表达。
## Config 方法
diff --git a/docs/next/workflows.md b/docs/next/workflows.md
index 47b4eb17..ee02023d 100644
--- a/docs/next/workflows.md
+++ b/docs/next/workflows.md
@@ -357,8 +357,8 @@ watch -> flash index -> search result -> Agent chooses document -> mineru parse
### 7.2 步骤
1. Agent 调用 search。
-2. doclib 查询文件名索引和内容索引。
-3. search result 返回路径、sha256、snippet、当前索引来源 tier。
+2. doclib 查询内容索引;文件名查询由 find 负责。
+3. search result 返回完整 file aliases、sha256、snippet、当前索引来源 tier。
4. Agent 选择具体文档。
5. Agent 发起主动 parse 请求。
6. PDF/image 请求未指定 tier 时使用默认选择策略;Office/text/HTML 按 `flash` 语义处理。
diff --git a/mineru/cli/commands/search.py b/mineru/cli/commands/search.py
index e35bc648..bc16545e 100644
--- a/mineru/cli/commands/search.py
+++ b/mineru/cli/commands/search.py
@@ -63,12 +63,20 @@ def _render_search_results(data: SearchResponse) -> str:
lines = [f"Search results ({data.total} total)"]
for index, result in enumerate(data.results, start=1):
- filename = result.title or result.filename or "?"
- path = _format_result_path(result.paths)
- item_line = f"{index}. {filename}{path}"
+ label = result.title or f"Document {result.short_id}"
+ item_line = f"{index}. {label}"
if result.tier:
item_line += f" Tier: {result.tier}"
lines.append(item_line)
+ active_files = [file for file in result.files if file.status == "active"]
+ display_files = active_files or result.files
+ if display_files:
+ lines.append(" Files:")
+ for file in display_files:
+ suffix = f" ({file.status})" if file.status != "active" else ""
+ lines.append(f" {file.path}{suffix}")
+ else:
+ lines.append(" File no longer exists.")
snippet = _format_snippet(result.snippet)
if snippet:
lines.append(f" {snippet}")
diff --git a/mineru/doclib/core/fts.py b/mineru/doclib/core/fts.py
index 62256743..28e80e37 100644
--- a/mineru/doclib/core/fts.py
+++ b/mineru/doclib/core/fts.py
@@ -55,7 +55,6 @@ class FTSManager:
text: str,
title: str,
author: str,
- filename: str,
) -> None:
"""Insert or replace content for a doc. Caller is responsible
for tier-gating (only call if new tier >= current)."""
@@ -64,9 +63,8 @@ class FTSManager:
[
("DELETE FROM fts_contents WHERE sha256=?", (sha256,)),
(
- "INSERT INTO fts_contents (sha256, tier, text, title, author, filename) "
- "VALUES (?, ?, ?, ?, ?, ?)",
- (sha256, tier, tokenized, title or "", author or "", filename),
+ "INSERT INTO fts_contents (sha256, tier, text, title, author) VALUES (?, ?, ?, ?, ?)",
+ (sha256, tier, tokenized, title or "", author or ""),
),
]
)
@@ -80,7 +78,7 @@ class FTSManager:
return cast(
list[FtsContentSearchRow],
await self.db.fetchall(
- "SELECT sha256, title, author, filename, tier, "
+ "SELECT sha256, title, author, tier, "
"snippet(fts_contents, 2, '<mark>', '</mark>', '...', 40) AS snippet, rank "
"FROM fts_contents WHERE fts_contents MATCH ? "
"ORDER BY rank LIMIT ?",
@@ -91,9 +89,7 @@ class FTSManager:
return []
async def get_tier(self, sha256: str) -> Tier | None:
- row = await self.db.fetchone(
- "SELECT tier FROM fts_contents WHERE sha256=?", (sha256,)
- )
+ row = await self.db.fetchone("SELECT tier FROM fts_contents WHERE sha256=?", (sha256,))
return cast(Tier, row["tier"]) if row else None
async def delete(self, sha256: str) -> None:
diff --git a/mineru/doclib/migrations/001_init.sql b/mineru/doclib/migrations/001_init.sql
index cce7d850..f7e5b055 100644
--- a/mineru/doclib/migrations/001_init.sql
+++ b/mineru/doclib/migrations/001_init.sql
@@ -96,7 +96,6 @@ CREATE VIRTUAL TABLE IF NOT EXISTS fts_contents USING fts5(
text,
title,
author,
- filename,
tokenize='unicode61'
);
diff --git a/mineru/doclib/rows.py b/mineru/doclib/rows.py
index db4d5559..74ee41be 100644
--- a/mineru/doclib/rows.py
+++ b/mineru/doclib/rows.py
@@ -186,7 +186,6 @@ class FtsContentSearchRow(TypedDict):
sha256: str
title: str
author: str
- filename: str
tier: Tier
snippet: str
rank: float
@@ -198,16 +197,16 @@ class FtsFilenameSearchRow(TypedDict):
snippet: str
-class SearchFileRow(FileRow):
+class FilenameSearchFileRow(FileRow):
title: str | None
- author: str | None
page_count: int | None
- file_type: str | None
-class FilenameSearchFileRow(FileRow):
- title: str | None
- page_count: int | None
+class SearchResultFileRow(TypedDict):
+ path: str
+ filename: str
+ ext: str
+ status: FileStatus
class ContentSearchResultRow(TypedDict):
@@ -215,13 +214,11 @@ class ContentSearchResultRow(TypedDict):
short_id: str
title: str | None
author: str | None
- filename: str | None
- ext: str | None
- size_bytes: int | None
+ size_bytes: int
page_count: int | None
tier: Tier
snippet: str
- paths: list[str]
+ files: list[SearchResultFileRow]
class FilenameSearchResultRow(TypedDict):
diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.py
index 7001f240..af1dbaa6 100644
--- a/mineru/doclib/services/parse_svc.py
+++ b/mineru/doclib/services/parse_svc.py
@@ -626,7 +626,6 @@ class ParseService:
text=truncate_head_tail(text),
title=metadata["title"] or "",
author=metadata["author"] or "",
- filename=filename,
)
return cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,)))
@@ -1312,7 +1311,6 @@ class ParseService:
text=text,
title=file_row.get("title") or "",
author=file_row.get("author") or "",
- filename=file_row["filename"],
)
async def _maybe_update_docs_meta(self, sha256: str, tier: Tier) -> None:
@@ -1371,7 +1369,6 @@ class ParseService:
text=text,
title=file_row.get("title") or "",
author=file_row.get("author") or "",
- filename=file_row["filename"],
)
return
diff --git a/mineru/doclib/services/search_svc.py b/mineru/doclib/services/search_svc.py
index cae9558d..c2692090 100644
--- a/mineru/doclib/services/search_svc.py
+++ b/mineru/doclib/services/search_svc.py
@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, cast
from ...types import TIER_ORDER, Tier
from ..core.db import DatabaseManager
from ..core.fts import FTSManager, strip_sep
-from ..rows import ContentSearchResultRow, FilenameSearchFileRow, FilenameSearchResultRow, SearchFileRow
+from ..rows import ContentSearchResultRow, DocRow, FileRow, FilenameSearchFileRow, FilenameSearchResultRow
from ..types import FILE_STATUS_ACTIVE
if TYPE_CHECKING:
@@ -45,23 +45,27 @@ class SearchService:
# dedup by sha256
sha256s = list(dict.fromkeys(r["sha256"] for r in rows))
- # join with docs + files
+ # Load document metadata independently so indexed orphan documents remain searchable.
placeholders = ",".join("?" * len(sha256s))
- sql = (
- "SELECT f.*, d.short_id, d.title, d.author, d.page_count, d.file_type "
- "FROM files f JOIN docs d ON f.sha256 = d.sha256 "
- f"WHERE f.sha256 IN ({placeholders})"
- )
+ doc_sql = f"SELECT * FROM docs WHERE sha256 IN ({placeholders})"
params = [*sha256s]
if file_type:
- sql += " AND d.file_type = ?"
+ doc_sql += " AND file_type = ?"
params.append(file_type.lower())
- file_rows = cast(list[SearchFileRow], await self.db.fetchall(sql, tuple(params)))
+ doc_rows = cast(list[DocRow], await self.db.fetchall(doc_sql, tuple(params)))
+ docs_by_sha = {row["sha256"]: row for row in doc_rows}
+ file_rows = cast(
+ list[FileRow],
+ await self.db.fetchall(
+ f"SELECT * FROM files WHERE sha256 IN ({placeholders}) ORDER BY id DESC",
+ tuple(sha256s),
+ ),
+ )
# group files by sha256
- files_by_doc: dict[str, list[SearchFileRow]] = {}
+ files_by_doc: dict[str, list[FileRow]] = {}
for fr in file_rows:
sha = fr["sha256"]
if sha is None:
@@ -74,29 +78,32 @@ class SearchService:
results: list[ContentSearchResultRow] = []
for row in rows:
sha = row["sha256"]
- all_files = files_by_doc.get(sha, [])
- if not all_files:
+ doc = docs_by_sha.get(sha)
+ if doc is None:
continue
-
- active_files = [file for file in all_files if file.get("status") == FILE_STATUS_ACTIVE]
- files = active_files or all_files
- fts_file = files[0]
+ all_files = files_by_doc.get(sha, [])
snippet = strip_sep(row.get("snippet", ""))
result_tier = row["tier"]
results.append(
{
"sha256": sha,
- "short_id": fts_file["short_id"],
- "title": row.get("title") or fts_file.get("title"),
- "author": row.get("author") or fts_file.get("author"),
- "filename": row.get("filename") or fts_file.get("filename"),
- "ext": fts_file.get("ext", ""),
- "size_bytes": fts_file.get("size_bytes", 0),
- "page_count": fts_file.get("page_count"),
+ "short_id": doc["short_id"],
+ "title": row.get("title") or doc.get("title"),
+ "author": row.get("author") or doc.get("author"),
+ "size_bytes": doc["size_bytes"],
+ "page_count": doc.get("page_count"),
"tier": result_tier,
"snippet": snippet,
- "paths": [f["path"] for f in files],
+ "files": [
+ {
+ "path": file["path"],
+ "filename": file["filename"],
+ "ext": file["ext"],
+ "status": file["status"],
+ }
+ for file in all_files
+ ],
}
)
diff --git a/mineru/doclib/types.py b/mineru/doclib/types.py
index 63a363ed..f9071442 100644
--- a/mineru/doclib/types.py
+++ b/mineru/doclib/types.py
@@ -318,18 +318,23 @@ class DocContentExportResponse(DoclibModel):
output: str
+class SearchFile(DoclibModel):
+ path: str
+ filename: str
+ ext: str
+ status: FileStatus
+
+
class SearchResult(DoclibModel):
sha256: str
short_id: str
title: str | None = None
author: str | None = None
- filename: str | None = None
- ext: str | None = None
size_bytes: int | None = None
page_count: int | None = None
tier: Tier
snippet: str
- paths: list[str] = Field(default_factory=list)
+ files: list[SearchFile] = Field(default_factory=list)
class FindResult(DoclibModel):
diff --git a/tests/unittest/test_cli_next_command_design.py b/tests/unittest/test_cli_next_command_design.py
index 02144c8b..32c5842e 100644
--- a/tests/unittest/test_cli_next_command_design.py
+++ b/tests/unittest/test_cli_next_command_design.py
@@ -45,6 +45,7 @@ from mineru.doclib.types import (
ParseResponse,
ScanListResponse,
ScanInfo,
+ SearchFile,
SearchResponse,
SearchResult,
ServerStatusResponse,
@@ -223,17 +224,17 @@ def test_search_results_render_as_list_without_table() -> None:
SearchResult(
sha256="a" * 64,
short_id="aaaaaaa",
- filename="resume.pdf",
tier="medium",
snippet="Python\nengineer",
- paths=["/tmp/resume.pdf"],
+ files=[SearchFile(path="/tmp/resume.pdf", filename="resume.pdf", ext="pdf", status="active")],
)
],
)
)
assert "Search results (1 total)" in rendered
- assert "1. resume.pdf (/tmp/resume.pdf) Tier: medium" in rendered
+ assert "1. Document aaaaaaa Tier: medium" in rendered
+ assert " Files:\n /tmp/resume.pdf" in rendered
assert " Python engineer" in rendered
assert "Snippet:" not in rendered
@@ -247,13 +248,12 @@ def test_search_result_snippet_preserves_fts_match_after_long_prefix() -> None:
SearchResult(
sha256="a" * 64,
short_id="aaaaaaa",
- filename="deepseek.pdf",
tier="flash",
snippet=(
"...on each node. Under this constraint, our MoE training framework can nearly "
"achieve full computation-communication overlap. <mark>Token</mark> <mark>Dropping</mark>"
),
- paths=["/tmp/deepseek.pdf"],
+ files=[SearchFile(path="/tmp/deepseek.pdf", filename="deepseek.pdf", ext="pdf", status="active")],
)
],
)
@@ -263,6 +263,56 @@ def test_search_result_snippet_preserves_fts_match_after_long_prefix() -> None:
assert "<mark>Dropping</mark>" in rendered
+def test_search_results_render_active_files_then_inactive_fallback_and_orphan() -> None:
+ rendered = search_mod._render_search_results(
+ SearchResponse(
+ total=3,
+ query="needle",
+ results=[
+ SearchResult(
+ sha256="a" * 64,
+ short_id="aaaaaaa",
+ title="Active document",
+ tier="high",
+ snippet="active",
+ files=[
+ SearchFile(path="/tmp/deleted.pdf", filename="deleted.pdf", ext="pdf", status="deleted"),
+ SearchFile(path="/tmp/active.pdf", filename="active.pdf", ext="pdf", status="active"),
+ ],
+ ),
+ SearchResult(
+ sha256="b" * 64,
+ short_id="bbbbbbb",
+ tier="medium",
+ snippet="inactive",
+ files=[
+ SearchFile(
+ path="/volume/unreachable.pdf",
+ filename="unreachable.pdf",
+ ext="pdf",
+ status="unreachable",
+ ),
+ SearchFile(path="/tmp/old.pdf", filename="old.pdf", ext="pdf", status="deleted"),
+ ],
+ ),
+ SearchResult(
+ sha256="c" * 64,
+ short_id="ccccccc",
+ tier="flash",
+ snippet="orphan",
+ files=[],
+ ),
+ ],
+ )
+ )
+
+ assert "/tmp/active.pdf" in rendered
+ assert "/tmp/deleted.pdf" not in rendered
+ assert "/volume/unreachable.pdf (unreachable)" in rendered
+ assert "/tmp/old.pdf (deleted)" in rendered
+ assert "3. Document ccccccc Tier: flash\n File no longer exists." in rendered
+
+
def test_list_renderers_return_tables(monkeypatch: Any) -> None:
monkeypatch.setattr(list_resources, "Table", _FakeTable)
parse = ParseInfo(
diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.py
index d17e788e..3bb7fd15 100644
--- a/tests/unittest/test_doclib_cache_semantics.py
+++ b/tests/unittest/test_doclib_cache_semantics.py
@@ -1598,8 +1598,8 @@ def test_ensure_ingested_rebinds_changed_text_file_to_new_sha(tmp_path: Path) ->
assert second is not None
assert second["sha256"] == hashlib.sha256(b"new content").hexdigest()
- fts_row = await db.fetchone("SELECT sha256, tier, filename FROM fts_contents WHERE sha256=?", (second["sha256"],))
- assert fts_row == {"sha256": second["sha256"], "tier": "flash", "filename": "note.txt"}
+ fts_row = await db.fetchone("SELECT sha256, tier FROM fts_contents WHERE sha256=?", (second["sha256"],))
+ assert fts_row == {"sha256": second["sha256"], "tier": "flash"}
asyncio.run(_run())
@@ -1917,7 +1917,7 @@ def test_search_filters_by_tier_min_tier_and_file_type(tmp_path: Path) -> None:
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
(str(tmp_path / filename), filename, filename.rsplit(".", 1)[1], 10, now, sha256, "active", now, now),
)
- await fts.replace(sha256=sha256, tier=tier, text="needle content", title="", author="", filename=filename)
+ await fts.replace(sha256=sha256, tier=tier, text="needle content", title="", author="")
exact_results, exact_total = await service.search("needle", tier="high")
min_results, min_total = await service.search("needle", min_tier="high")
@@ -1930,14 +1930,46 @@ def test_search_filters_by_tier_min_tier_and_file_type(tmp_path: Path) -> None:
assert min_total == 2
assert {row["tier"] for row in min_results} == {"high", "xhigh"}
assert type_total == 1
- assert [row["filename"] for row in type_results] == ["flash.docx"]
+ assert [[file["filename"] for file in row["files"]] for row in type_results] == [["flash.docx"]]
assert [row["short_id"] for row in type_results] == ["3" * 7]
assert [row["page_count"] for row in type_results] == [23]
asyncio.run(_run())
-def test_search_prefers_active_paths_and_falls_back_to_non_active_paths(tmp_path: Path) -> None:
+def test_content_search_does_not_match_filename_but_find_does(tmp_path: Path) -> None:
+ async def _run() -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+ await db.initialize()
+ fts = FTSManager(db)
+ service = SearchService(db, fts)
+ sha256 = "f" * 64
+ now = 1000
+ await db.execute(
+ "INSERT INTO docs (sha256, short_id, size_bytes, file_type, first_seen_at, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?)",
+ (sha256, sha256[:7], 10, "pdf", now, now),
+ )
+ file_id = await db.execute_insert(
+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, first_seen_at, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ (str(tmp_path / "filenameonly.pdf"), "filenameonly.pdf", "pdf", 10, now, sha256, "active", now, now),
+ )
+ await fts.replace(sha256=sha256, tier="high", text="body content", title="", author="")
+ await fts.upsert_filename(file_id, "filenameonly.pdf", "pdf")
+
+ content_results, content_total = await service.search("filenameonly")
+ filename_results, filename_total = await service.search_filenames("filenameonly")
+
+ assert content_results == []
+ assert content_total == 0
+ assert filename_total == 1
+ assert [result["filename"] for result in filename_results] == ["filenameonly.pdf"]
+
+ asyncio.run(_run())
+
+
+def test_search_returns_all_files_in_reverse_insertion_order(tmp_path: Path) -> None:
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
@@ -1946,16 +1978,15 @@ def test_search_prefers_active_paths_and_falls_back_to_non_active_paths(tmp_path
now = 1000
sha_active = "4" * 64
sha_deleted = "5" * 64
+ sha_orphan = "6" * 64
- for sha256 in (sha_active, sha_deleted):
+ for sha256 in (sha_active, sha_deleted, sha_orphan):
await db.execute(
"INSERT INTO docs (sha256, short_id, size_bytes, file_type, page_count, first_seen_at, updated_at) "
"VALUES (?, ?, ?, ?, ?, ?, ?)",
(sha256, sha256[:7], 10, "pdf", 7 if sha256 == sha_active else 9, now, now),
)
- await fts.replace(
- sha256=sha256, tier="high", text="fallback needle", title="", author="", filename=f"{sha256[0]}.pdf"
- )
+ await fts.replace(sha256=sha256, tier="high", text="fallback needle", title="", author="")
await db.execute(
"INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, first_seen_at, updated_at) "
@@ -1974,12 +2005,22 @@ def test_search_prefers_active_paths_and_falls_back_to_non_active_paths(tmp_path
)
results, total = await service.search("fallback")
- paths_by_sha = {row["sha256"]: row["paths"] for row in results}
+ files_by_sha = {row["sha256"]: row["files"] for row in results}
- assert total == 2
- assert paths_by_sha[sha_active] == [str(tmp_path / "active.pdf")]
- assert paths_by_sha[sha_deleted] == [str(tmp_path / "deleted-only.pdf")]
- assert {row["sha256"]: row["page_count"] for row in results} == {sha_active: 7, sha_deleted: 9}
+ assert total == 3
+ assert [(file["filename"], file["status"]) for file in files_by_sha[sha_active]] == [
+ ("deleted-copy.pdf", "deleted"),
+ ("active.pdf", "active"),
+ ]
+ assert [(file["filename"], file["status"]) for file in files_by_sha[sha_deleted]] == [
+ ("deleted-only.pdf", "deleted")
+ ]
+ assert files_by_sha[sha_orphan] == []
+ assert {row["sha256"]: row["page_count"] for row in results} == {
+ sha_active: 7,
+ sha_deleted: 9,
+ sha_orphan: 9,
+ }
asyncio.run(_run())
@@ -3353,10 +3394,7 @@ def test_forget_path_deletes_file_row_and_filename_fts_without_deleting_doc(tmp_
"INSERT INTO parses (sha256, tier, page_range, status, privacy, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
(sha256, "high", "1", "done", "local", now, now),
)
- await db.execute(
- "INSERT INTO fts_contents (sha256, tier, text, filename) VALUES (?, ?, ?, ?)",
- (sha256, "high", "content", "doc.pdf"),
- )
+ await db.execute("INSERT INTO fts_contents (sha256, tier, text) VALUES (?, ?, ?)", (sha256, "high", "content"))
await db.execute(
"INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, first_seen_at, updated_at) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
diff --git a/tests/unittest/test_doclib_interface_contract.py b/tests/unittest/test_doclib_interface_contract.py
index d66cf7d5..32c03546 100644
--- a/tests/unittest/test_doclib_interface_contract.py
+++ b/tests/unittest/test_doclib_interface_contract.py
@@ -50,6 +50,7 @@ from mineru.doclib.types import (
RemoveParsingRuleResponse,
RemoveWatchResponse,
SearchResponse,
+ SearchFile,
SearchResult,
ServerStatusResponse,
ShutdownResponse,
@@ -481,10 +482,9 @@ def test_core_doclib_schemas_are_instantiable() -> None:
search_result = SearchResult(
sha256="abc",
short_id="abc",
- filename="a.pdf",
tier="high",
snippet="matched text",
- paths=["/tmp/a.pdf"],
+ files=[SearchFile(path="/tmp/a.pdf", filename="a.pdf", ext="pdf", status="active")],
)
find_result = FindResult(filename="a.pdf", ext="pdf", size_bytes=123, page_count=3, paths=["/tmp/a.pdf"])
search_response = SearchResponse(results=[search_result], total=1, query="matched")