Skip to content

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

feat(doclib): add paginated filename search and unified page selectors

myhloliaca9b06da3e4
diff --git a/docs/next/cli/mineru-e2e-test-cases.md b/docs/next/cli/mineru-e2e-test-cases.md
index 9af2f6f1..5492a870 100644
--- a/docs/next/cli/mineru-e2e-test-cases.md
+++ b/docs/next/cli/mineru-e2e-test-cases.md
@@ -2463,7 +2463,7 @@ mineru find "sample" --limit 1 --json
- exit code = 0
- stdout 为可直接解析的 JSON
- limit 生效,单次返回结果数量不超过 1
-- `find` 当前只承诺文件名查询、扩展名过滤、limit 和 JSON 输出;offset 契约单独由 SEARCH-013 覆盖
+- `total` 为过滤及状态刷新后的全部有效匹配数,不因 limit=1 缩小;offset 契约由 SEARCH-013 覆盖
### SEARCH-008 search type filter
@@ -3326,8 +3326,9 @@ mineru find "sample" --limit 1 --offset 1 --json
预期:
-- 如果 CLI 设计支持 find offset,exit code = 0,stdout 为可直接解析的 JSON,返回数量不超过 1
-- 如果 CLI 设计不支持 find offset,exit code != 0,输出包含 no such option、unknown option 或等价错误
+- exit code = 0,stdout 为可直接解析的 JSON,返回数量不超过 1
+- 结果对应稳定排序中的第二条有效匹配;`total` 与 offset=0 时一致
+- 超过末尾的 offset 返回空列表及正确总数;负 offset 或非正 limit 返回校验错误
- 不包含 Python traceback
### PARSE-016 page range 边界
diff --git a/docs/next/cli/mineru-library.md b/docs/next/cli/mineru-library.md
index e8c6eba8..11752c07 100644
--- a/docs/next/cli/mineru-library.md
+++ b/docs/next/cli/mineru-library.md
@@ -55,15 +55,20 @@ JSON 输出中的每条结果至少包含:
```bash
mineru find "report"
mineru find "report" --ext pdf
+mineru find "report" --ext pdf --limit 50 --offset 100
```
行为:
- 查询 `fts_filenames` 和文件 metadata。
- 支持按 `ext` 过滤。
+- 默认对最后一个查询词进行前缀匹配,例如 `bench` 可匹配 `bench1.pdf`;多词查询仅最后一词匹配前缀。显式 `bench*` 等价。
+- 支持 `--limit/-n`(默认 50)和 `--offset`(默认 0);limit 必须为正,offset 必须非负。
+- 在扩展名过滤、文件状态刷新后分页,`total` 表示全部有效匹配数,不受单页大小或 200 条候选上限影响。
+- 按相关性及 file id 稳定排序;同一 SHA256 的不同文件路径仍是独立搜索结果。
- 可返回同一 SHA256 的多个路径。
- 可用于解析前确认目标文件。
-- 当前 `find` 只暴露 `--ext`、`--limit/-n` 和 `--json`。
+- 超出结果末尾时返回空列表及正确的总数。
`find` JSON 输出中的每条结果至少包含:
diff --git a/docs/next/cli/mineru-read.md b/docs/next/cli/mineru-read.md
index c513c944..01dbfff3 100644
--- a/docs/next/cli/mineru-read.md
+++ b/docs/next/cli/mineru-read.md
@@ -30,7 +30,7 @@ mineru read <locator> [flags]
当前 P0 支持:
```bash
-mineru read <locator> [--format markdown|image] [--limit 30000] [--context N] [--output PATH] [--json] [--no-marker]
+mineru read <locator> [--after CURSOR] [--format markdown|image] [--limit 30000] [--context N] [--output PATH] [--json] [--no-marker]
```
## 3. Locator 输入
@@ -40,7 +40,7 @@ mineru read <locator> [--format markdown|image] [--limit 30000] [--context N] [-
```text
doc:{short_id}
doc:{short_id}/tier:{tier}
-doc:{short_id}/tier:{tier}/page:{page_no}
+doc:{short_id}/tier:{tier}/page:{page_selection}
doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}
doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}/char:{offset}
```
@@ -50,8 +50,17 @@ doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}/char:{offset}
- `short_id` 是 doclib 为文档生成的稳定短 ID。
- `tier` 取值为 `flash`、`basic`、`standard`、`advanced`。
- `page_no` 和 `block_no` 使用 1-based 编号。
+- `page_selection` 与解析输入页范围共用语法:数字、`rN`、区间、逗号组合和 `all`。`r1` 为最后一页;倒数页和 `all` 必须有可靠的文档总页数。
+- 页选择排序、去重并裁剪越界页;返回的规范定位器和块引用使用实际页码。带 block/char 时必须解析为单页。
- `char:{offset}` 使用 block 渲染文本内的 0-based 字符 offset。
+```bash
+mineru read doc:ab12cd3/tier:flash/page:r1
+mineru read doc:ab12cd3/tier:flash/page:r3-r1
+mineru read doc:ab12cd3/tier:flash/page:1,3,r1
+mineru read doc:ab12cd3/tier:flash/page:all
+```
+
当只给出 `doc:{short_id}` 时,系统不会创建新解析,而是在当前已缓存的非 `flash` 质量 tier 中选择最高质量结果,顺序为 `advanced` -> `standard` -> `basic`。如果不存在非 `flash` 质量 tier 结果,则返回错误,不静默降级到 `flash`。
## 4. 核心参数
@@ -61,6 +70,7 @@ doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}/char:{offset}
| `--format`, `-f` | `markdown` / `image` | `markdown` | 输出 content format |
| `--json` | bool | false | 将整个 CLI 响应包装为 JSON |
| `--limit` | int | `30000` | 文本输出软字符上限 |
+| `--after` | locator | 不传 | 使用范围读取返回的实际页码游标继续读取;要求 Markdown 页选择且 context=0 |
| `--context` | int | `0` | 按 locator 周围扩展上下文 |
| `--output`, `-o` | path | 不传 | 将返回内容或 image asset 写入本地路径;image 只支持 `.png`、`.jpg`、`.jpeg`、`.webp` |
| `--no-marker` | bool | false | 关闭 continuation marker |
@@ -106,6 +116,7 @@ Markdown 继续优先输出 table、chart 和 formula 的结构化内容。需
| char locator | 按 block locator 处理上下文,char 只影响起点 |
| doc locator | 返回 `context_not_applicable` |
| doc/tier locator | 返回 `context_not_applicable` |
+| 多页选择 | 非零 context 返回 `context_not_applicable` |
## 6. Image 读取
@@ -148,7 +159,8 @@ locator-first 读取时:
- `request_scope.locator` 为规范化 locator。
- `request_scope.context` 为实际生效的 context。
-- `next_request` 只写 `locator`。
+- 单点读取的 `next_request` 使用 `locator`;范围内截断时同时返回 `locator` 和 `after`。
+- 多页选择只读取范围内的已缓存内容,读完后 `next_request=null`;不会创建新解析或继续推荐范围外页面。
## 8. Continuation
@@ -162,6 +174,14 @@ locator-first 读取时:
`--json` 时,通过 `next_request.locator` 表示下一次建议读取的位置。
+范围读取的续读保留原选择,并以实际页码的块/字符游标推进。例如:
+
+```text
+<!-- Next: mineru read doc:ab12cd3/tier:flash/page:1,3 --after doc:ab12cd3/tier:flash/page:1/block:2/char:1000 -->
+```
+
+可以直接执行该命令;第 2 页不会因续读被加入。图片读取要求页选择解析为单页,多页选择返回 `multi_page_image_not_supported`。
+
## 9. 与 mineru parse 的关系
建议工作流:
diff --git a/docs/next/decisions/0005-doclib-interface-client-server-contract.md b/docs/next/decisions/0005-doclib-interface-client-server-contract.md
index 0b804376..f2703f7d 100644
--- a/docs/next/decisions/0005-doclib-interface-client-server-contract.md
+++ b/docs/next/decisions/0005-doclib-interface-client-server-contract.md
@@ -107,7 +107,7 @@ def search(
limit: int = 20,
offset: int = 0,
) -> SearchResponse: ...
-def find(self, query: str, *, ext: str | None = None, limit: int = 50) -> FindResponse: ...
+def find(self, query: str, *, ext: str | None = None, limit: int = 50, offset: int = 0) -> FindResponse: ...
def get_file_by_path(self, path: str) -> FileInfoResponse: ...
```
diff --git a/docs/next/decisions/0012-doclib-block-locator.md b/docs/next/decisions/0012-doclib-block-locator.md
index 327f399b..6bc3deff 100644
--- a/docs/next/decisions/0012-doclib-block-locator.md
+++ b/docs/next/decisions/0012-doclib-block-locator.md
@@ -48,6 +48,14 @@ doc:ab12cd3/tier:basic/page:1/block:3
| `page_no` | 1-based 页号。 |
| `block_no` | 1-based block 号。 |
+### 请求页选择与稳定块引用
+
+`read_content()` 请求定位器的 `page:` 部分复用解析输入页范围语法:单页数字、`rN`、区间、逗号组合和 `all`。例如 `page:r1` 是最后一页,`page:r3-r1` 是最后三页,`page:1,3,r1` 是第一、第三及最后一页。倒数页和 `all` 必须依据文档总页数求值,不从部分缓存推算。
+
+求值、排序、去重和越界裁剪复用 DocVortex 公共页范围算法。响应定位器及生成的 block reference 始终使用实际 1-based 页码;`ContentCursor.page_no` 保持整数,不把范围加入稳定块引用协议。带 `/block:`、`/char:` 或图片读取时,选择必须解析为单页;多页选择不接受非零 context。
+
+范围截断时,`next_request` 保留规范化页范围定位器并携带绝对块/字符 `after`,供下一次 `read_content(locator, after=...)` 使用。续读只访问原范围内尚未完成的内容,结束后不推荐范围外页面。已有数字单点定位及单点读取的续读行为保持不变,不新增 `page:last` 别名。
+
## Block 编号来源
`block_no` 来自 Middle JSON 中 block 自身的稳定编号,或 canonical Middle JSON page 内的稳定 block 序列。
diff --git a/docs/next/decisions/0014-mineru-read-command.md b/docs/next/decisions/0014-mineru-read-command.md
index bc987af6..af137663 100644
--- a/docs/next/decisions/0014-mineru-read-command.md
+++ b/docs/next/decisions/0014-mineru-read-command.md
@@ -21,7 +21,7 @@ mineru read <locator>
新增 `mineru read` 顶级命令:
```bash
-mineru read <locator> [--format markdown|image] [--limit 30000] [--context N] [--output PATH] [--json] [--no-marker]
+mineru read <locator> [--after CURSOR] [--format markdown|image] [--limit 30000] [--context N] [--output PATH] [--json] [--no-marker]
```
`parse` 与 `read` 的职责边界:
@@ -60,6 +60,8 @@ doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}/char:{offset}
- `doc:{short_id}` 会解析为当前可用的默认高质量 tier;不会静默把 `flash` 当作高质量读取结果。
- `doc:{short_id}/tier:{tier}` 明确读取指定 tier 的已有结果。
+请求定位器的 `page:` 同步采用输入页范围语法:数字、`rN`、区间、逗号组合与 `all`,具体规则见 [ADR-0012](0012-doclib-block-locator.md#请求页选择与稳定块引用)。返回引用仍使用实际页码;block/char 和图片读取必须选择单页,多页选择不支持非零 context。
+
## Markdown 读取语义
> visual block 的 Markdown 引用与 image 可用性规则已由 [ADR-0027](0027-doclib-visual-block-locators.md) 补充;`image_path` 不再作为 doclib 用户接口暴露。
@@ -168,7 +170,8 @@ class DocContentResponse(DoclibModel):
- locator read 的 `request_scope.locator` 填入规范化 locator。
- locator read 的 `request_scope.context` 填入实际生效的 context。
- parse read 的 `next_request` 只写 `page_range` / `after`,不写 `locator`。
-- read 的 `next_request` 只写 `locator`,不写 `page_range` / `after`。
+- 单点 read 的 `next_request` 只写 `locator`;范围内截断时保留范围 `locator` 并携带绝对块/字符 `after`,可通过 `mineru read <locator> --after <cursor>` 继续读取。
+- 范围 read 读完后 `next_request=null`,续读不会进入未选择的页面;已有单点 read 的续读行为保持不变。
- image 输出时 `content=""`,asset 信息写入 `asset`,不把图片路径塞进 `content`。
parse read 返回示例:
diff --git a/docs/next/sdk/doclib-client.md b/docs/next/sdk/doclib-client.md
index ab09e619..05e4778c 100644
--- a/docs/next/sdk/doclib-client.md
+++ b/docs/next/sdk/doclib-client.md
@@ -123,7 +123,7 @@ class ParseResponse:
| `list_parses(*, ids=None, doc_ref=None, tier=None, status=None, page_range=None, include_superseded=False, limit=50, offset=0)` | 对应 `GET /parses`,按 ids、`doc_ref`、tier、status 或 page_range 查询 parse records 和覆盖状态;`include_superseded` 控制是否返回已被覆盖的 parse。 |
| `get_parse(parse_id)` | 对应 `GET /parses/{id}`,查询单条 parse record。 |
| `get_doc_content(doc_ref, *, tier, page_range=None, after=None, limit=30000, format="markdown", no_marker=False)` | 对应 `GET /docs/{doc_ref}/content`,从保存的 JSON 结果读取时转换。 |
-| `read_content(locator, *, context=0, limit=30000, format="markdown", image_format="jpeg", no_marker=False)` | 对应 `GET /content`,按 Agent locator 读取内容或图片。 |
+| `read_content(locator, *, after=None, context=0, limit=30000, format="markdown", image_format="jpeg", no_marker=False)` | 对应 `GET /content`,按单点或页范围 locator 读取内容或图片。 |
| `export_doc_content(doc_ref, request)` | 对应 `POST /docs/{doc_ref}/exports`,导出结构化内容。 |
| `invalidate(request)` | 对应 `POST /invalidate`,将已有解析结果标记为失效;不自动触发重新解析。 |
@@ -133,6 +133,16 @@ class ParseResponse:
Markdown 响应中的 visual block 图片使用 `doc:.../page:.../block:...` locator。非空图片 locator 可以原样传给 `read_content(..., format="image")`;空 locator 表示该 block 没有可用图片。SDK 调用方不应依赖或拼接 Middle JSON 内部的 `image_path`。
+请求定位器的 `page:` 复用输入页范围语法:数字、`rN`、`1-5`、`r3-r1`、`1,3,r1`、`all`。`r1` 表示最后一页,`rN` 和 `all` 需要文档总页数;返回定位器及块引用使用实际页码。带 block/char、图片读取和非零 context 都要求选中单页。
+
+范围读取结束后 `next_request=null`。范围内截断时,同时返回规范化 `locator` 和实际页码 `after`;两者可直接传给下一次 `read_content()`,不会读入未选择的页面:
+
+```python
+result = client.read_content("doc:ab12cd3/tier:flash/page:1,3", limit=1000)
+if result.next_request is not None:
+ result = client.read_content(result.next_request.locator, after=result.next_request.after, limit=1000)
+```
+
## Search 与文件信息
```python
@@ -147,7 +157,7 @@ def search(
offset: int = 0,
) -> SearchResponse: ...
-def find(self, query: str, *, ext: str | None = None, limit: int = 50) -> FindResponse: ...
+def find(self, query: str, *, ext: str | None = None, limit: int = 50, offset: int = 0) -> FindResponse: ...
def get_file_by_path(self, path: str) -> FileInfoResponse: ...
```
@@ -159,11 +169,13 @@ def get_file_by_path(self, path: str) -> FileInfoResponse: ...
| 方法 | 响应 |
|------|------|
| `search()` | `SearchResponse`,包含全文结果、snippet、files、可空 tier;支持 `file_type`、`tier`、`min_tier` 过滤。 |
-| `find()` | `FindResponse`,包含文件名搜索结果;支持 `ext` 过滤。 |
+| `find()` | `FindResponse`,包含文件名前缀搜索结果;支持 `ext` 过滤及 `limit/offset` 分页。 |
| `get_file_by_path()` | `FileInfoResponse`,包含文件元信息、doc metadata 和 parse tiers。 |
`search()` 的 `files` 返回与文档 SHA 关联的全部 file aliases,按 file id 降序排列;每项包含 path、filename、ext 和 status。已索引的 orphan 文档使用空列表。active 优先只属于非 JSON CLI 展示策略,不改变 SDK 响应。解析内容的 `tier` 表示索引来源 tier;直接索引的 text 源内容为 `null`。传入 `tier` 或 `min_tier` 时,`tier=null` 的结果不参与匹配。
+`find()` 默认仅对最后一个分词应用前缀匹配,显式尾部 `*` 等价。结果按相关性及 file id 排序,在扩展名过滤和文件状态刷新后计算 `total` 并分页。`limit` 必须为正整数,`offset` 必须为非负整数;偏移超过末尾时仍返回完整有效匹配数。HTTP `GET /api/v1/find` 接受同名参数,同步与异步接口保持一致。
+
## Remote API 方法
| 方法 | 响应 |
diff --git a/mineru/cli/commands/read.py b/mineru/cli/commands/read.py
index 3b2b839f..a59c2d26 100644
--- a/mineru/cli/commands/read.py
+++ b/mineru/cli/commands/read.py
@@ -24,7 +24,11 @@ class ReadTextOutput:
def read_cmd(
- locator: str = typer.Argument(..., help=t("Document library locator, e.g. doc:ab12cd3/tier:basic/page:4")),
+ locator: str = typer.Argument(
+ ...,
+ help=t("Document library locator; page selection supports numbers, rN, ranges, comma-separated pages and all"),
+ ),
+ after: str | None = typer.Option(None, "--after", help=t("Continue reading after a content cursor from earlier output")),
context: int = typer.Option(0, "--context", help=t("Read N pages/blocks before and after the locator")),
limit: int = typer.Option(30000, "--limit", help=t("Soft character limit for printed content")),
format: Literal["markdown", "image"] = typer.Option("markdown", "-f", "--format", help=t("Output format: markdown, image")),
@@ -32,12 +36,13 @@ def read_cmd(
no_marker: bool = typer.Option(False, "--no-marker", help=t("Omit continuation marker from output")),
json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
- """Read parsed doclib content by locator."""
+ """按单点或页范围定位读取内容,并支持范围内续读。"""
ctx = CliContext(json_mode=json_mode)
run_cli(
ctx,
lambda: _read(
locator,
+ after=after,
context=context,
limit=limit,
format=format,
@@ -57,7 +62,9 @@ def _read(
output: str | None,
no_marker: bool,
json_mode: bool,
+ after: str | None = None,
) -> DocContentResponse | dict[str, object] | CliResult[ReadTextOutput] | CliResult[None]:
+ """调用内容服务;只有显式续读时才传入 after,保持普通调用参数兼容。"""
image_format = _image_format_for_output(format=format, output=output) if format == "image" else "jpeg"
client = DoclibClient(timeout=60)
if format == "image":
@@ -68,6 +75,7 @@ def _read(
format=format,
image_format=image_format,
no_marker=no_marker,
+ **({"after": after} if after is not None else {}),
)
else:
content = client.read_content(
@@ -76,6 +84,7 @@ def _read(
limit=limit,
format=format,
no_marker=no_marker,
+ **({"after": after} if after is not None else {}),
)
return _prepare_read_output(content, json_mode=json_mode, output=output, no_marker=no_marker)
@@ -160,6 +169,8 @@ def _image_format_for_output(*, format: Literal["markdown", "image"], output: st
def _read_next_marker(next_request: ContentNextRequest) -> str | None:
+ """把范围定位和绝对游标一起写入可直接执行的续读命令。"""
if not next_request.locator:
return None
- return f"<!-- Next: mineru read {next_request.locator} -->"
+ after_option = f" --after {next_request.after}" if next_request.after else ""
+ return f"<!-- Next: mineru read {next_request.locator}{after_option} -->"
diff --git a/mineru/cli/commands/search.py b/mineru/cli/commands/search.py
index c1523507..4be22a18 100644
--- a/mineru/cli/commands/search.py
+++ b/mineru/cli/commands/search.py
@@ -48,12 +48,13 @@ def find_cmd(
query: str = typer.Argument(..., help=t("Filename search query")),
ext: str | None = typer.Option(None, "--ext", help=t("File extension filter: {exts}", exts=FILE_EXTS)),
limit: int = typer.Option(50, "--limit", "-n", help=t("Max results")),
+ offset: int = typer.Option(0, "--offset", help=t("Result offset")),
json_mode: bool = typer.Option(False, "--json", help=t("JSON output")),
) -> None:
- """Search filenames only (not document content)."""
+ """按文件名前缀搜索,并按有效匹配的顺序分页。"""
run_cli(
CliContext(json_mode=json_mode),
- lambda: DoclibClient(timeout=10).find(query, ext=ext, limit=limit),
+ lambda: DoclibClient(timeout=10).find(query, ext=ext, limit=limit, offset=offset),
render=_render_find_results,
)
diff --git a/mineru/doclib/base.py b/mineru/doclib/base.py
index a5be8c74..78ff2e49 100644
--- a/mineru/doclib/base.py
+++ b/mineru/doclib/base.py
@@ -286,13 +286,14 @@ class DoclibInterface(ABC):
self,
locator: str,
*,
+ after: str | None = None,
context: int = 0,
limit: int = 30000,
format: ContentFormat = "markdown",
image_format: ImageFormat = "jpeg",
no_marker: bool = False,
) -> DocContentResponse:
- """Render stored doc content from a stable content locator.
+ """按定位器读取内容;范围定位可携带实际页码游标继续读取。
Raises:
NotFoundError: when the document or requested parsed content is not cached.
@@ -334,11 +335,11 @@ class DoclibInterface(ABC):
raise NotImplementedError()
@abstractmethod
- def find(self, query: str, *, ext: str | None = None, limit: int = 50) -> FindResponse:
- """Search filenames.
+ def find(self, query: str, *, ext: str | None = None, limit: int = 50, offset: int = 0) -> FindResponse:
+ """按文件名前缀搜索,在有效文件过滤后按 limit/offset 分页。
Raises:
- InvalidRequestError: when query, ext, or limit is invalid.
+ InvalidRequestError: when query, ext, limit, or offset is invalid.
MineruError: for search backend failures.
"""
raise NotImplementedError()
@@ -676,13 +677,14 @@ class AsyncDoclibInterface(ABC):
self,
locator: str,
*,
+ after: str | None = None,
context: int = 0,
limit: int = 30000,
format: ContentFormat = "markdown",
image_format: ImageFormat = "jpeg",
no_marker: bool = False,
) -> DocContentResponse:
- """Async version of ``DoclibInterface.read_content``."""
+ """异步按定位器读取内容,并使用实际页码游标在范围内续读。"""
raise NotImplementedError()
@abstractmethod
@@ -705,8 +707,8 @@ class AsyncDoclibInterface(ABC):
raise NotImplementedError()
@abstractmethod
- async def find(self, query: str, *, ext: str | None = None, limit: int = 50) -> FindResponse:
- """Async version of ``DoclibInterface.find``."""
+ async def find(self, query: str, *, ext: str | None = None, limit: int = 50, offset: int = 0) -> FindResponse:
+ """异步执行与同步接口一致的文件名前缀搜索和分页。"""
raise NotImplementedError()
@abstractmethod
diff --git a/mineru/doclib/client.py b/mineru/doclib/client.py
index 57ace97b..7b7267d9 100644
--- a/mineru/doclib/client.py
+++ b/mineru/doclib/client.py
@@ -259,16 +259,19 @@ class DoclibClient(DoclibInterface):
self,
locator: str,
*,
+ after: str | None = None,
context: int = 0,
limit: int = 30000,
format: ContentFormat = "markdown",
image_format: ImageFormat = "jpeg",
no_marker: bool = False,
) -> DocContentResponse:
+ """传递页范围定位与可选续读游标,单点调用保持原有语义。"""
return self._request_model(
DocContentResponse,
params={
"locator": locator,
+ "after": after,
"context": context,
"limit": limit,
"format": format,
@@ -306,8 +309,9 @@ class DoclibClient(DoclibInterface):
)
@route("GET", "/find", tags=("search",))
- def find(self, query: str, *, ext: str | None = None, limit: int = 50) -> FindResponse:
- return self._request_model(FindResponse, params={"query": query, "ext": ext, "limit": limit})
+ def find(self, query: str, *, ext: str | None = None, limit: int = 50, offset: int = 0) -> FindResponse:
+ """将文件名查询和分页参数传给统一 Doclib 服务。"""
+ return self._request_model(FindResponse, params={"query": query, "ext": ext, "limit": limit, "offset": offset})
@route("GET", "/files/by-path", tags=("files",))
def get_file_by_path(self, path: str) -> FileInfoResponse:
diff --git a/mineru/doclib/core/fts.py b/mineru/doclib/core/fts.py
index acde20d4..35e2c201 100644
--- a/mineru/doclib/core/fts.py
+++ b/mineru/doclib/core/fts.py
@@ -108,21 +108,27 @@ class FTSManager:
]
)
- async def search_filenames(self, query: str, limit: int = 50) -> list[FtsFilenameSearchRow]:
+ async def search_filenames(self, query: str, limit: int | None = 50) -> list[FtsFilenameSearchRow]:
+ """仅对文件名查询的最后一个词默认启用前缀匹配;None 获取完整候选快照。"""
tokens = _sanitize_query_tokens(tokenize_for_query(query))
if not tokens:
return []
+ if not query.rstrip().endswith("*"):
+ tokens[-1] += "*"
fts_query = " ".join(tokens)
+ sql = (
+ "SELECT file_id, ext, "
+ "snippet(fts_filenames, 1, '<mark>', '</mark>', '...', 40) AS snippet "
+ "FROM fts_filenames WHERE fts_filenames MATCH ? ORDER BY rank, file_id"
+ )
+ params: tuple[str | int, ...] = (fts_query,)
+ if limit is not None:
+ sql += " LIMIT ?"
+ params += (limit,)
try:
return cast(
list[FtsFilenameSearchRow],
- await self.db.fetchall(
- "SELECT file_id, ext, "
- "snippet(fts_filenames, 1, '<mark>', '</mark>', '...', 40) AS snippet "
- "FROM fts_filenames WHERE fts_filenames MATCH ? "
- "ORDER BY rank LIMIT ?",
- (fts_query, limit),
- ),
+ await self.db.fetchall(sql, params),
)
except Exception:
return []
diff --git a/mineru/doclib/server.py b/mineru/doclib/server.py
index 52e1a18d..4ee50532 100644
--- a/mineru/doclib/server.py
+++ b/mineru/doclib/server.py
@@ -10,7 +10,7 @@ import signal
import sys
import time
from collections.abc import Callable
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from pathlib import Path
from typing import Any, cast
from urllib.parse import urlparse
@@ -23,6 +23,7 @@ from ..config import config
from ..errors import InvalidRequestError, MineruError, NotFoundError, error_response, http_status_for
from ..filetypes import IMAGE_EXTENSIONS, TEXT_EXTENSIONS, TEXT_FILE_TYPES
from ..parser.page_range import (
+ count_pages_in_range,
expand_page_range as _expand_page_range,
format_page_range as _page_numbers_to_range_str,
normalize_page_range_input,
@@ -224,6 +225,8 @@ class _LocatorParts:
page_no: int | None = None
block_no: int | None = None
char_offset: int | None = None
+ page_range: str | None = None
+ range_selection: bool = False
class DoclibServer(AsyncDoclibInterface):
@@ -631,12 +634,14 @@ class DoclibServer(AsyncDoclibInterface):
self,
locator: str,
*,
+ after: str | None = None,
context: int = 0,
limit: int = 30000,
format: ContentFormat = "markdown",
image_format: ImageFormat = "jpeg",
no_marker: bool = False,
) -> DocContentResponse:
+ """读取共享语法的页选择;范围续读只访问选择中的未完成内容。"""
start_ms = _now_ms()
dims = {"content_mode": "read", "output_format": _telemetry_output_format(format), "tier": "unknown"}
await _record_telemetry_count(self.state, "content.request.count", dimensions=dims)
@@ -644,6 +649,7 @@ class DoclibServer(AsyncDoclibInterface):
response = await self._execute_read_plan(
await self._build_read_plan_from_locator(
locator,
+ after=after,
context=context,
limit=limit,
format=format,
@@ -705,7 +711,9 @@ class DoclibServer(AsyncDoclibInterface):
format: ContentFormat,
image_format: ImageFormat,
no_marker: bool,
+ after: str | None = None,
) -> _ReadPlan:
+ """将页选择解析为实际页范围,同时保持单点块和图片的定位约束。"""
limit = max(1, limit)
context = max(0, context)
cursor = _parse_doc_locator(locator)
@@ -718,6 +726,7 @@ class DoclibServer(AsyncDoclibInterface):
"Text files do not require MinerU parsing. Read the file directly.",
"locator",
)
+ cursor = _resolve_locator_pages(cursor, doc)
tier = cursor.tier or await self._default_read_tier(doc["sha256"])
if tier is None:
@@ -728,16 +737,32 @@ class DoclibServer(AsyncDoclibInterface):
)
if format == "image" and context:
raise InvalidRequestError("context_not_applicable", "context is not supported for image reads.", "context")
+ if cursor.page_range and count_pages_in_range(cursor.page_range) > 1:
+ if cursor.block_no is not None:
+ raise InvalidRequestError("invalid_locator", "Block and char locators require a single page.", "locator")
+ if format == "image":
+ raise InvalidRequestError("multi_page_image_not_supported", "image format supports only one page.", "locator")
+ if context:
+ raise InvalidRequestError("context_not_applicable", "context requires a single page.", "context")
if cursor.page_no is None and context:
raise InvalidRequestError("context_not_applicable", "context requires a page, block, or char locator.", "context")
page_range = _locator_page_range(cursor, doc, context)
+ if after is not None:
+ if cursor.page_range is None or cursor.block_no is not None or context or format != "markdown":
+ raise InvalidRequestError(
+ "invalid_request", "after requires a Markdown page selection without context.", "after"
+ )
+ after_cursor = _parse_after_cursor(after)
+ if after_cursor is None:
+ raise InvalidRequestError("invalid_locator", "after must be a non-empty content cursor.", "after")
+ _validate_cursor_for_doc(after_cursor, doc, tier, page_range)
return _ReadPlan(
sha256=doc["sha256"],
short_id=doc["short_id"],
tier=tier,
page_range=page_range,
- after=_locator_after(cursor, tier),
+ after=after if after is not None else _locator_after(cursor, tier),
locator=_canonical_locator(doc["short_id"], tier, cursor),
context=context,
limit=limit,
@@ -753,7 +778,9 @@ class DoclibServer(AsyncDoclibInterface):
)
if cursor.page_no is not None
else None,
- next_mode="read",
+ next_mode="range"
+ if (cursor.range_selection and cursor.block_no is None and not context) or after is not None
+ else "read",
)
@route("POST", "/docs/{doc_ref}/exports", tags=("docs",))
@@ -823,7 +850,8 @@ class DoclibServer(AsyncDoclibInterface):
raise
@route("GET", "/find", tags=("search",))
- async def find(self, query: str, *, ext: str | None = None, limit: int = 50) -> FindResponse:
+ async def find(self, query: str, *, ext: str | None = None, limit: int = 50, offset: int = 0) -> FindResponse:
+ """返回完整有效匹配数,并按调用方指定的偏移量分页。"""
start_ms = _now_ms()
await _record_telemetry_count(self.state, "find.request.count")
try:
@@ -831,6 +859,7 @@ class DoclibServer(AsyncDoclibInterface):
query=query,
ext=ext,
limit=limit,
+ offset=offset,
refresh_file=self.state.parse_svc.refresh_file,
)
response = FindResponse(results=[_find_result(row) for row in results], total=total, query=query)
@@ -1306,17 +1335,18 @@ class DoclibServer(AsyncDoclibInterface):
page_count = doc["page_count"] if doc else None
paginated = _is_paginated_doc(doc) if doc else True
- next_request = (
- _next_read_request(rendered, plan.short_id, plan.tier, page_count)
- if plan.next_mode == "read"
- else _next_content_request(
+ if plan.next_mode == "range":
+ next_request = _next_range_read_request(rendered, plan.locator)
+ elif plan.next_mode == "read":
+ next_request = _next_read_request(rendered, plan.short_id, plan.tier, page_count)
+ else:
+ next_request = _next_content_request(
rendered=rendered,
request_page_range=plan.page_range,
after=plan.after,
page_count=page_count,
paginated=paginated,
)
- )
return DocContentResponse(
sha256=plan.sha256,
short_id=plan.short_id,
@@ -1509,28 +1539,56 @@ class DoclibServer(AsyncDoclibInterface):
_READ_LOCATOR_RE = re.compile(
r"^doc:(?P<short_id>[0-9a-fA-F]+)"
r"(?:/tier:(?P<tier>flash|basic|standard|advanced)"
- r"(?:/page:(?P<page_no>[1-9][0-9]*)"
+ r"(?:/page:(?P<page_range>[^/]+)"
r"(?:/block:(?P<block_no>[1-9][0-9]*)(?:/char:(?P<char_offset>0|[1-9][0-9]*))?)?)?)?$"
)
def _parse_doc_locator(locator: str) -> _LocatorParts:
+ """只解析输入语法,倒数页和范围在获取文档页数后统一求值。"""
match = _READ_LOCATOR_RE.match(locator)
if match is None:
raise InvalidRequestError("invalid_locator", f"Invalid doclib locator: {locator}", "locator")
- page_no = match.group("page_no")
+ page_range = match.group("page_range")
+ if page_range is not None:
+ if not page_range.strip():
+ raise InvalidRequestError("invalid_locator", "Page selection cannot be empty.", "locator")
+ try:
+ normalized_range = normalize_page_range_input(page_range)
+ except InvalidRequestError as error:
+ raise InvalidRequestError("invalid_locator", error.message, "locator") from error
+ else:
+ normalized_range = None
block_no = match.group("block_no")
char_offset = match.group("char_offset")
return _LocatorParts(
short_id=match.group("short_id"),
tier=cast(Tier | None, match.group("tier")),
- page_no=int(page_no) if page_no is not None else None,
+ page_no=int(normalized_range) if normalized_range and normalized_range.isdecimal() else None,
block_no=int(block_no) if block_no is not None else None,
char_offset=int(char_offset) if char_offset is not None else None,
+ page_range=normalized_range,
+ range_selection=page_range is not None and (page_range.strip() == "all" or "," in page_range or "-" in page_range),
)
+def _resolve_locator_pages(locator: _LocatorParts, doc: DocRow) -> _LocatorParts:
+ """复用公共页范围算法求值;倒数页和 all 禁止用部分缓存猜测总页数。"""
+ if locator.page_range is None:
+ return locator
+ page_count = doc.get("page_count")
+ if (page_count is None or page_count < 1) and ("r" in locator.page_range or locator.page_range == "all"):
+ raise InvalidRequestError(
+ "invalid_locator", "Cannot resolve all/rN because the document page count is unavailable.", "locator"
+ )
+ resolved_range = _expand_page_range(locator.page_range, page_count or 1)
+ single_page = count_pages_in_range(resolved_range) == 1
+ return replace(locator, page_range=resolved_range, page_no=int(resolved_range) if single_page else None)
+
+
def _canonical_locator(short_id: str, tier: Tier, locator: _LocatorParts) -> str:
+ if locator.range_selection and locator.page_range is not None and locator.block_no is None:
+ return f"doc:{short_id}/tier:{tier}/page:{locator.page_range}"
if locator.page_no is None:
return f"doc:{short_id}/tier:{tier}"
if locator.block_no is None:
@@ -1550,6 +1608,8 @@ def _locator_after(locator: _LocatorParts, tier: Tier) -> str | None:
def _locator_page_range(locator: _LocatorParts, doc: DocRow, context: int) -> str | None:
page_count = doc.get("page_count") or 1
+ if locator.page_range is not None and not context:
+ return locator.page_range
if locator.page_no is None:
return _normalize_content_page_range(None, None, doc)
if locator.page_no > page_count:
@@ -2106,6 +2166,13 @@ def _next_read_request(
return ContentNextRequest(locator=page_ref(short_id, tier, next_page_no))
+def _next_range_read_request(rendered: _RenderedContent, locator: str | None) -> ContentNextRequest | None:
+ """保留范围定位器并推进实际页码游标,避免续读扩入未选择的页面。"""
+ if not rendered.truncated or not rendered.content_ranges or locator is None:
+ return None
+ return ContentNextRequest(locator=locator, after=rendered.content_ranges[-1].end)
+
+
def _last_requested_page(page_range: str | None) -> int | None:
if not page_range:
return None
diff --git a/mineru/doclib/services/search_svc.py b/mineru/doclib/services/search_svc.py
index 69b861f2..b58128da 100644
--- a/mineru/doclib/services/search_svc.py
+++ b/mineru/doclib/services/search_svc.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING, Any, cast
+from ...errors import InvalidRequestError
from ...types import TIER_ORDER, Tier
from ..core.db import DatabaseManager
from ..core.fts import FTSManager, strip_sep
@@ -15,6 +16,7 @@ if TYPE_CHECKING:
from .parse_svc import FileRefreshResult
FilenamePathProbe = Callable[[str], Awaitable["FileRefreshResult"]]
+_FILENAME_METADATA_BATCH_SIZE = 256
class SearchService:
@@ -113,54 +115,65 @@ class SearchService:
# ── filename search ─────────────────────────────────────────
async def search_filenames(
- self, query: str, ext: str | None = None, limit: int = 50, *, refresh_file: FilenamePathProbe | None = None
+ self,
+ query: str,
+ ext: str | None = None,
+ limit: int = 50,
+ offset: int = 0,
+ *,
+ refresh_file: FilenamePathProbe | None = None,
) -> tuple[list[FilenameSearchResultRow], int]:
- """Search filenames only. Returns (results, total_count)."""
- rows = await self.fts.search_filenames(query, limit=limit)
+ """完整候选按固定顺序分批刷新,在有效文件过滤后统计总数并分页。"""
+ if isinstance(limit, bool) or not isinstance(limit, int) or limit < 1:
+ raise InvalidRequestError("invalid_request", "limit must be a positive integer.", "limit")
+ if isinstance(offset, bool) or not isinstance(offset, int) or offset < 0:
+ raise InvalidRequestError("invalid_request", "offset must be a non-negative integer.", "offset")
+ rows = await self.fts.search_filenames(query, limit=None)
if not rows:
return [], 0
- file_ids = [r["file_id"] for r in rows]
- placeholders = ",".join("?" * len(file_ids))
- sql = (
- f"SELECT f.*, d.title, d.page_count "
- f"FROM files f LEFT JOIN docs d ON f.sha256 = d.sha256 "
- f"WHERE f.id IN ({placeholders})"
- )
- params: list[Any] = [*file_ids]
- if refresh_file is None:
- sql += " AND f.status = ?"
- params.append(FILE_STATUS_ACTIVE)
- if ext:
- sql += " AND f.ext = ?"
- params.append(ext.lower().lstrip("."))
- file_rows = cast(list[FilenameSearchFileRow], await self.db.fetchall(sql, tuple(params)))
- if refresh_file is not None:
- file_rows = await self._filter_probe_stale_filename_rows(file_rows, refresh_file)
-
- files_by_id = {fr["id"]: fr for fr in file_rows}
-
+ normalized_ext = ext.lower().lstrip(".") if ext else None
results: list[FilenameSearchResultRow] = []
- for row in rows:
- fr = files_by_id.get(row["file_id"])
- if not fr:
- continue
- results.append(
- {
- "sha256": fr.get("sha256", ""),
- "title": fr.get("title"),
- "filename": fr["filename"],
- "ext": fr.get("ext", ""),
- "size_bytes": fr.get("size_bytes", 0),
- "page_count": fr.get("page_count"),
- "tier": "",
- "snippet": strip_sep(row.get("snippet", "")),
- "paths": [fr["path"]],
- }
+ for start in range(0, len(rows), _FILENAME_METADATA_BATCH_SIZE):
+ batch = rows[start : start + _FILENAME_METADATA_BATCH_SIZE]
+ file_ids = [row["file_id"] for row in batch]
+ placeholders = ",".join("?" * len(file_ids))
+ sql = (
+ "SELECT f.*, d.title, d.page_count "
+ "FROM files f LEFT JOIN docs d ON f.sha256 = d.sha256 "
+ f"WHERE f.id IN ({placeholders})"
)
+ params: list[Any] = [*file_ids]
+ if refresh_file is None:
+ sql += " AND f.status = ?"
+ params.append(FILE_STATUS_ACTIVE)
+ if normalized_ext:
+ sql += " AND f.ext = ?"
+ params.append(normalized_ext)
+ file_rows = cast(list[FilenameSearchFileRow], await self.db.fetchall(sql, tuple(params)))
+ if refresh_file is not None:
+ file_rows = await self._filter_probe_stale_filename_rows(file_rows, refresh_file)
+ files_by_id = {file["id"]: file for file in file_rows}
+ for row in batch:
+ file = files_by_id.get(row["file_id"])
+ if file is None or (normalized_ext and file["ext"] != normalized_ext):
+ continue
+ results.append(
+ {
+ "sha256": file.get("sha256", ""),
+ "title": file.get("title"),
+ "filename": file["filename"],
+ "ext": file.get("ext", ""),
+ "size_bytes": file.get("size_bytes", 0),
+ "page_count": file.get("page_count"),
+ "tier": "",
+ "snippet": strip_sep(row.get("snippet", "")),
+ "paths": [file["path"]],
+ }
+ )
total = len(results)
- return results, total
+ return results[offset : offset + limit], total
async def _filter_probe_stale_filename_rows(
self,
diff --git a/mineru/utils/translations.py b/mineru/utils/translations.py
index d9af6e20..82ba205d 100644
--- a/mineru/utils/translations.py
+++ b/mineru/utils/translations.py
@@ -69,6 +69,9 @@ ZH_MESSAGES: dict[str, str] = {
"{label}: {ids}": "{label}: {ids}",
# ------------------------------------------------------------------ read
"Document library locator, e.g. doc:ab12cd3/tier:basic/page:4": "文档库定位符,如 doc:ab12cd3/tier:basic/page:4",
+ "Document library locator; page selection supports numbers, rN, ranges, comma-separated pages and all": (
+ "文档库定位符;页选择支持数字、rN、区间、逗号组合和 all"
+ ),
"Read N pages/blocks before and after the locator": "在定位符前后各读取 N 页/块",
"Output format: markdown, image": "输出格式: markdown、image",
"Omit continuation marker from output": "输出中省略续读标记",
diff --git a/tests/unittest/test_doclib_find_pagination.py b/tests/unittest/test_doclib_find_pagination.py
new file mode 100644
index 00000000..de7d7107
--- /dev/null
+++ b/tests/unittest/test_doclib_find_pagination.py
@@ -0,0 +1,226 @@
+"""验证文件名前缀、完整候选分页及 HTTP/SDK/CLI 的参数一致性。"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import httpx
+import pytest
+from typer.testing import CliRunner
+
+from mineru.cli.commands import search as search_commands
+from mineru.cli.main import app
+from mineru.doclib.client import DoclibClient
+from mineru.doclib.core.db import DatabaseManager
+from mineru.doclib.core.fts import FTSManager, tokenize_for_index
+from mineru.doclib.server import DoclibServer
+from mineru.doclib.services.parse_svc import FileRefreshResult
+from mineru.doclib.services.search_svc import SearchService
+from mineru.doclib.types import FindResponse
+from mineru.errors import InvalidRequestError
+
+
+async def _filename_library(tmp_path: Path, filenames: list[str]) -> tuple[DatabaseManager, FTSManager, SearchService]:
+ """一次事务建立真实 FTS 与文件记录,路径不同的同名文件保留独立身份。"""
+ db = DatabaseManager(str(tmp_path / "library.sqlite"))
+ await db.initialize()
+ statements: list[tuple[str, tuple[Any, ...]]] = []
+ for file_id, filename in enumerate(filenames, start=1):
+ ext = Path(filename).suffix.lstrip(".")
+ statements.extend(
+ [
+ (
+ "INSERT INTO files (id, path, filename, ext, size_bytes, mtime_ms, first_seen_at, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
+ (file_id, str(tmp_path / str(file_id) / filename), filename, ext, 10, 1, 1, 1),
+ ),
+ (
+ "INSERT INTO fts_filenames (file_id, filename, ext) VALUES (?, ?, ?)",
+ (file_id, tokenize_for_index(filename), ext),
+ ),
+ ]
+ )
+ await db.execute_atomic(statements)
+ fts = FTSManager(db)
+ return db, fts, SearchService(db, fts)
+
+
+def test_filename_prefix_is_applied_only_to_final_token(tmp_path: Path) -> None:
+ """前缀查询覆盖中文和多词,显式星号等价且正文索引不自动补前缀。"""
+
+ async def run() -> None:
+ """在真实 SQLite FTS 上比较隐式与显式前缀查询。"""
+ db, fts, _ = await _filename_library(
+ tmp_path,
+ ["bench1.pdf", "bench5.pdf", "annual report2026.pdf", "项目报告2026.pdf", "annualized report2026.pdf"],
+ )
+ try:
+ await fts.replace(sha256="f" * 64, tier="standard", text="benchmark content", title="", author="")
+ for query in ("bench", "bench*", "bench* "):
+ assert [row["file_id"] for row in await fts.search_filenames(query)] == [1, 2]
+ assert [row["file_id"] for row in await fts.search_filenames("annual rep")] == [3]
+ assert [row["file_id"] for row in await fts.search_filenames("项目报告")] == [4]
+ assert [row["file_id"] for row in await fts.search_filenames("bench1")] == [1]
+ assert await fts.search_filenames(" ") == []
+ assert await fts.search("bench") == []
+ assert len(await fts.search("benchmark")) == 1
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
+def test_find_paginates_all_candidates_in_stable_order(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """六百余条同分候选跨过旧上限与元信息批次,每页无遗漏且总数不随 limit 变化。"""
+
+ async def run() -> None:
+ """记录元信息查询批次,同时遍历真实搜索的所有分页。"""
+ db, _, service = await _filename_library(tmp_path, ["report.pdf"] * 601)
+ batch_sizes: list[int] = []
+ fetchall = db.fetchall
+
+ async def record_fetchall(sql: str, params: tuple[Any, ...] | None = None) -> list[dict[str, Any]]:
+ """只观察元信息批大小,不替换实际 SQL 结果。"""
+ if "WHERE f.id IN" in sql:
+ batch_sizes.append(sum(isinstance(value, int) for value in params or ()))
+ return await fetchall(sql, params)
+
+ monkeypatch.setattr(db, "fetchall", record_fetchall)
+ try:
+ paths: list[str] = []
+ for offset in range(0, 601, 97):
+ rows, total = await service.search_filenames("report", limit=97, offset=offset)
+ assert total == 601
+ paths.extend(row["paths"][0] for row in rows)
+ assert paths == [str(tmp_path / str(index) / "report.pdf") for index in range(1, 602)]
+ assert max(batch_sizes) == 256
+ assert await service.search_filenames("report", limit=50, offset=601) == ([], 601)
+ assert await service.search_filenames("missing", limit=50, offset=10) == ([], 0)
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
+def test_find_filters_and_refreshes_before_pagination(tmp_path: Path) -> None:
+ """删除前面的索引记录不会使后续批次漏项,扩展名与有效文件数均先于分页生效。"""
+
+ async def run() -> None:
+ """刷新期间删除 FTS 行,验证分页依赖最初的有序候选快照。"""
+ filenames = ["report.pdf"] * 270 + ["report.docx"] * 10
+ db, fts, service = await _filename_library(tmp_path, filenames)
+ refreshed_ids: list[int] = []
+
+ async def refresh(path: str) -> FileRefreshResult:
+ """把前三个路径标记为删除,同时移除其 FTS 行。"""
+ file_id = int(Path(path).parent.name)
+ refreshed_ids.append(file_id)
+ if file_id <= 3:
+ await db.execute("UPDATE files SET status='deleted' WHERE id=?", (file_id,))
+ await fts.delete_filename(file_id)
+ return FileRefreshResult(file=None, status="deleted")
+ return FileRefreshResult(file=None, status="known")
+
+ try:
+ rows, total = await service.search_filenames("report", ext=".PDF", limit=10, offset=260, refresh_file=refresh)
+ assert total == 267
+ assert [int(Path(row["paths"][0]).parent.name) for row in rows] == list(range(264, 271))
+ assert refreshed_ids == list(range(1, 271))
+ rows, total = await service.search_filenames("report", ext="pdf", limit=2)
+ assert total == 267
+ assert [int(Path(row["paths"][0]).parent.name) for row in rows] == [4, 5]
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
[email protected](("limit", "offset", "param"), [(0, 0, "limit"), (-1, 0, "limit"), (50, -1, "offset")])
+def test_find_rejects_invalid_pagination(tmp_path: Path, limit: int, offset: int, param: str) -> None:
+ """非法参数在查询前返回明确的产品校验错误。"""
+
+ async def run() -> None:
+ """空索引也必须校验分页参数。"""
+ db, _, service = await _filename_library(tmp_path, [])
+ try:
+ with pytest.raises(InvalidRequestError) as error:
+ await service.search_filenames("report", limit=limit, offset=offset)
+ assert error.value.param == param
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
+def test_find_http_exposes_offset_and_validates_pagination(tmp_path: Path) -> None:
+ """HTTP 参数、默认值、总数和错误结构与服务层一致。"""
+
+ async def run() -> None:
+ """通过实际 ASGI 路由请求文件名查询。"""
+ db, _, service = await _filename_library(tmp_path, ["report.pdf"] * 4)
+
+ async def refresh(path: str) -> FileRefreshResult:
+ """保留已有有效记录,让接口走正常刷新边界。"""
+ return FileRefreshResult(file=None, status="known")
+
+ server = DoclibServer(SimpleNamespace(db=db, search_svc=service, parse_svc=SimpleNamespace(refresh_file=refresh)))
+ try:
+ parameters = server.app.openapi()["paths"]["/api/v1/find"]["get"]["parameters"]
+ assert next(item for item in parameters if item["name"] == "offset")["schema"]["default"] == 0
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=server.app), base_url="http://test") as client:
+ response = await client.get("/api/v1/find", params={"query": "report", "limit": 2, "offset": 2})
+ assert response.status_code == 200
+ assert response.json()["total"] == 4
+ assert [int(Path(row["paths"][0]).parent.name) for row in response.json()["results"]] == [3, 4]
+ invalid = await client.get("/api/v1/find", params={"query": "report", "offset": -1})
+ assert invalid.status_code == 400
+ assert invalid.json()["error"]["param"] == "offset"
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
+def test_find_sdk_transmits_offset(monkeypatch: pytest.MonkeyPatch) -> None:
+ """公共同步 SDK 在请求中传递分页字段,而非只改变函数签名。"""
+ calls: list[dict[str, Any]] = []
+
+ def send_request(self: DoclibClient, method: str, path: str, *, params: dict[str, Any], json_data: Any) -> httpx.Response:
+ """捕获实际 HTTP 参数,返回合法的文件名搜索响应。"""
+ calls.append(params)
+ return httpx.Response(
+ 200, request=httpx.Request(method, f"http://test{path}"), json={"results": [], "total": 601, "query": "report"}
+ )
+
+ monkeypatch.setattr(DoclibClient, "_send_request", send_request)
+ client = DoclibClient(base_url="http://test")
+ try:
+ assert client.find("report", ext="pdf", limit=10, offset=200).total == 601
+ assert calls == [{"query": "report", "ext": "pdf", "limit": 10, "offset": 200}]
+ finally:
+ client.close()
+
+
+def test_find_cli_passes_offset(monkeypatch: pytest.MonkeyPatch) -> None:
+ """真实 Typer 命令把 --offset 传递到 SDK,并保留默认 limit。"""
+ calls: list[dict[str, Any]] = []
+
+ class Client:
+ """只替换外部连接,保留完整的 CLI 参数解析。"""
+
+ def __init__(self, *, timeout: int) -> None:
+ """验证查询命令沿用原有超时设置。"""
+ assert timeout == 10
+
+ def find(self, query: str, **kwargs: Any) -> FindResponse:
+ """记录 CLI 提交的分页参数。"""
+ calls.append({"query": query, **kwargs})
+ return FindResponse(results=[], total=300, query=query)
+
+ monkeypatch.setattr(search_commands, "DoclibClient", Client)
+ result = CliRunner().invoke(app, ["find", "report", "--ext", "pdf", "--offset", "200", "--json"])
+ assert result.exit_code == 0
+ assert calls == [{"query": "report", "ext": "pdf", "limit": 50, "offset": 200}]
diff --git a/tests/unittest/test_doclib_page_selection.py b/tests/unittest/test_doclib_page_selection.py
new file mode 100644
index 00000000..e0a1c416
--- /dev/null
+++ b/tests/unittest/test_doclib_page_selection.py
@@ -0,0 +1,432 @@
+"""验证共享页选择语法、单点约束以及范围内可直接执行的续读请求。"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import re
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import httpx
+import pytest
+from typer.testing import CliRunner
+
+from mineru.cli.commands import read as read_commands
+from mineru.cli.main import app
+from mineru.doclib.client import DoclibClient
+from mineru.doclib.core.db import DatabaseManager
+from mineru.doclib.locators import parse_content_cursor
+from mineru.doclib.server import DoclibServer, _ReadPlan
+from mineru.doclib.services.parse_svc import parse_batch_json_path
+from mineru.doclib.types import ContentAsset, ContentNextRequest, ContentRequestScope, DocContentResponse
+from mineru.errors import InvalidRequestError, NotFoundError
+from mineru.parser.page_range import format_page_range
+from mineru.types import MiddleJson, PageInfo, TextBlock
+
+_SHORT_ID = "aaaaaaa"
+_SHA256 = "a" * 64
+_DOC_REF = f"doc:{_SHORT_ID}/tier:flash"
+
+
+def _page(page_idx: int, *texts: str) -> PageInfo:
+ """用稳定块号构造带几何信息的缓存页面。"""
+ return PageInfo(
+ page_idx=page_idx,
+ blocks=[
+ TextBlock(
+ type="text",
+ index=index,
+ bbox=(0.0, 0.0, 0.1, 0.1),
+ content=[{"type": "text", "content": text}],
+ )
+ for index, text in enumerate(texts)
+ ],
+ )
+
+
+async def _cached_library(
+ tmp_path: Path, *, page_count: int | None = 12, pages: list[PageInfo] | None = None
+) -> tuple[DatabaseManager, DoclibServer]:
+ """写入真实新版缓存;总页数与已缓存页范围可以独立设置。"""
+ db = DatabaseManager(str(tmp_path / "library.sqlite"))
+ await db.initialize()
+ await db.execute(
+ "INSERT INTO docs (sha256, short_id, size_bytes, file_type, page_count, first_seen_at, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?)",
+ (_SHA256, _SHORT_ID, 12, "pdf", page_count, 1, 1),
+ )
+ if pages is None:
+ pages = [_page(index, f"PAGE{index + 1:02}") for index in range(page_count or 1)]
+ page_range = format_page_range(page.page_idx + 1 for page in pages)
+ await db.execute(
+ "INSERT INTO parses (sha256, tier, page_range, status, done_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
+ (_SHA256, "flash", page_range, "done", 1, 1, 1),
+ )
+ middle = MiddleJson(
+ pages=pages,
+ is_full_document=page_count == len(pages),
+ metadata={"file_suffix": "pdf", "producer": {"name": "mineru", "version": "test"}},
+ extensions={"mineru": {"tier": "flash", "parse_mode": "txt"}},
+ )
+ cache_path = Path(parse_batch_json_path(str(tmp_path), _SHA256, "flash", page_range, 1))
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
+ cache_path.write_text(json.dumps(middle.to_dict(), ensure_ascii=False), encoding="utf-8")
+ return db, DoclibServer(SimpleNamespace(db=db, data_dir=str(tmp_path)))
+
+
+ ("selection", "expected_range", "expected_pages"),
+ [
+ ("r1", "12", [12]),
+ ("r2", "11", [11]),
+ ("1-5", "1-5", [1, 2, 3, 4, 5]),
+ ("r3-r1", "10-12", [10, 11, 12]),
+ ("1,3,r1", "1,3,12", [1, 3, 12]),
+ ("all", "1-12", list(range(1, 13))),
+ ("1-99,3", "1-12", list(range(1, 13))),
+ ("3,1,3", "1,3", [1, 3]),
+ ],
+)
+def test_read_page_selection_is_resolved_and_canonical(
+ tmp_path: Path, selection: str, expected_range: str, expected_pages: list[int]
+) -> None:
+ """所有页选择共享排序、去重和裁剪规则,返回引用均使用实际页码。"""
+
+ async def run() -> None:
+ """通过真实缓存读取检查请求范围和实际输出页面。"""
+ db, server = await _cached_library(tmp_path)
+ try:
+ result = await server.read_content(f"{_DOC_REF}/page:{selection}", no_marker=True)
+ assert result.request_scope.page_range == expected_range
+ assert result.request_scope.locator == f"{_DOC_REF}/page:{expected_range}"
+ assert result.content.split("\n\n") == [f"PAGE{page_no:02}" for page_no in expected_pages]
+ if len(expected_pages) > 1 or selection == "all":
+ assert result.next_request is None
+ elif expected_pages[-1] < 12:
+ assert result.next_request is not None
+ assert result.next_request.locator == f"{_DOC_REF}/page:{expected_pages[-1] + 1}"
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
[email protected]("selection", ["0", "r0", "last", "3-1", "-1", "1~3", "1,,3", " "])
+def test_read_rejects_invalid_page_selection(tmp_path: Path, selection: str) -> None:
+ """定位器不引入 last、旧分隔符或与输入页范围不同的非法语法。"""
+
+ async def run() -> None:
+ """验证非法定位在读取缓存前返回产品错误。"""
+ db, server = await _cached_library(tmp_path)
+ try:
+ with pytest.raises(InvalidRequestError):
+ await server.read_content(f"{_DOC_REF}/page:{selection}")
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
[email protected]("selection", ["r1", "r3-r1", "all"])
+def test_relative_selection_requires_known_total(tmp_path: Path, selection: str) -> None:
+ """部分缓存不能用于猜测最后一页或完整文档的范围。"""
+
+ async def run() -> None:
+ """建立只有第一页的缓存,但文档总页数未知。"""
+ db, server = await _cached_library(tmp_path, page_count=None)
+ try:
+ with pytest.raises(InvalidRequestError) as error:
+ await server.read_content(f"{_DOC_REF}/page:{selection}")
+ assert error.value.param == "locator"
+ assert "page count is unavailable" in error.value.message
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
+def test_single_relative_page_supports_blocks_chars_and_context(tmp_path: Path) -> None:
+ """倒数单页仍能定位块、字符以及邻页,返回稳定的绝对引用。"""
+
+ async def run() -> None:
+ """检查单点扩展与既有块读取行为一致。"""
+ db, server = await _cached_library(tmp_path)
+ try:
+ block = await server.read_content(f"{_DOC_REF}/page:r1/block:1", no_marker=True)
+ assert block.content == "PAGE12"
+ assert block.request_scope.locator == f"{_DOC_REF}/page:12/block:1"
+ char = await server.read_content(f"{_DOC_REF}/page:r1/block:1/char:4", no_marker=True)
+ assert char.content == "12"
+ assert char.request_scope.after == f"{_DOC_REF}/page:12/block:1/char:4"
+ context = await server.read_content(f"{_DOC_REF}/page:r1", context=1, no_marker=True)
+ assert context.request_scope.page_range == "11-12"
+ assert context.content == "PAGE11\n\nPAGE12"
+ singleton = await server.read_content(f"{_DOC_REF}/page:12-99/block:1", no_marker=True)
+ assert singleton.request_scope.locator == f"{_DOC_REF}/page:12/block:1"
+ assert singleton.content == "PAGE12"
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
+ ("suffix", "options", "param"),
+ [
+ ("/block:1", {}, "locator"),
+ ("/block:1/char:0", {}, "locator"),
+ ("", {"format": "image"}, "locator"),
+ ("", {"context": 1}, "context"),
+ ],
+)
+def test_multi_page_selection_rejects_single_target_options(
+ tmp_path: Path, suffix: str, options: dict[str, Any], param: str
+) -> None:
+ """多页范围不能同时表示一个块、字符、图片或带上下文的单点目标。"""
+
+ async def run() -> None:
+ """检查单点约束在加载缓存及生成图片之前生效。"""
+ db, server = await _cached_library(tmp_path)
+ try:
+ with pytest.raises(InvalidRequestError) as error:
+ await server.read_content(f"{_DOC_REF}/page:1,3{suffix}", **options)
+ assert error.value.param == param
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
+def test_relative_page_image_uses_resolved_page(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """图片读取把倒数页解析为实际页码后再交给原有素材边界。"""
+
+ async def run() -> None:
+ """替换实际裁图,检查素材调用获得的页号与响应引用。"""
+ db, server = await _cached_library(tmp_path)
+ captured: list[int] = []
+
+ async def render_asset(plan: _ReadPlan, page: PageInfo) -> ContentAsset:
+ """记录素材调用目标,不初始化 PDFium。"""
+ assert plan.target is not None
+ captured.append(plan.target.page_no)
+ return ContentAsset(path=str(tmp_path / "page.png"), mime_type="image/png")
+
+ monkeypatch.setattr(server, "_render_source_image_asset", render_asset)
+ try:
+ result = await server.read_content(f"{_DOC_REF}/page:r1", format="image")
+ assert captured == [12]
+ assert result.request_scope.locator == f"{_DOC_REF}/page:12"
+ assert result.content_ranges[0].page_range == "12"
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
+ ("limit", "texts"),
+ [
+ (20, [("A" * 20,), ("FORBIDDEN",), ("Z" * 20,)]),
+ (35, [("A" * 20, "B" * 20), ("FORBIDDEN",), ("Z" * 20,)]),
+ (7, [("ABCDEFGHIJKLMNO",), ("FORBIDDEN",), ("xyz0123456789",)]),
+ ],
+)
[email protected]("selection", ["1,3", "1-3"])
[email protected]("no_marker", [True, False])
+def test_range_continuation_preserves_pages_blocks_and_chars(
+ tmp_path: Path, limit: int, texts: list[tuple[str, ...]], selection: str, no_marker: bool
+) -> None:
+ """逐次执行返回的续读请求,验证页间、块间和字符截断均不漏、不重、不扩页。"""
+
+ async def run() -> None:
+ """通过真实缓存和游标循环重建选定页面的全部正文。"""
+ pages = [_page(index, *items) for index, items in enumerate(texts)]
+ db, server = await _cached_library(tmp_path, page_count=4, pages=pages)
+ try:
+ locator = f"{_DOC_REF}/page:{selection}"
+ after = None
+ chunks: list[str] = []
+ for _ in range(30):
+ result = await server.read_content(locator, after=after, limit=limit, no_marker=no_marker)
+ assert result.request_scope.page_range == selection
+ if selection == "1,3":
+ assert "FORBIDDEN" not in result.content
+ body = re.sub(r"<!-- page [0-9]+(?: of [0-9]+)? -->\n*", "", result.content)
+ chunks.append(body.replace("\n\n", ""))
+ if result.next_request is None:
+ break
+ assert result.truncated
+ assert result.next_request.locator == locator
+ assert result.next_request.after is not None
+ cursor = parse_content_cursor(result.next_request.after)
+ assert cursor.page_no in ({1, 3} if selection == "1,3" else {1, 2, 3})
+ assert result.next_request.after != after
+ after = result.next_request.after
+ else:
+ pytest.fail("范围续读未能在有限次数内完成")
+ selected_texts = texts[0] + texts[2] if selection == "1,3" else texts[0] + texts[1] + texts[2]
+ assert "".join(chunks) == "".join(selected_texts)
+ assert not result.truncated
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
+def test_range_reads_only_cached_selected_pages(tmp_path: Path) -> None:
+ """部分缓存只输出选中的已缓存页面,不推测或引入其他页。"""
+
+ async def run() -> None:
+ """选择跨过未缓存页,末尾仍按本次范围结束。"""
+ db, server = await _cached_library(tmp_path, pages=[_page(0, "FIRST"), _page(2, "THIRD")])
+ try:
+ result = await server.read_content(f"{_DOC_REF}/page:1-3", no_marker=True)
+ assert result.content == "FIRST\n\nTHIRD"
+ assert result.request_scope.page_range == "1-3"
+ assert result.next_request is None
+ with pytest.raises(NotFoundError):
+ await server.read_content(f"{_DOC_REF}/page:2")
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
[email protected](("selection", "page_count"), [("1-1", 4), ("1,1", 4), ("all", 1)])
+def test_single_page_range_continuation_stays_bounded(tmp_path: Path, selection: str, page_count: int) -> None:
+ """范围规范化为一个数字后,携带 after 的续读仍须在该范围内结束。"""
+
+ async def run() -> None:
+ """保留后续缓存页,确保单页范围不会退回旧的单点继续推荐行为。"""
+ pages = [_page(0, "abcdefghijklmnop")]
+ if page_count > 1:
+ pages.append(_page(1, "OUTSIDE"))
+ db, server = await _cached_library(tmp_path, page_count=page_count, pages=pages)
+ try:
+ locator = f"{_DOC_REF}/page:{selection}"
+ after = None
+ chunks: list[str] = []
+ for _ in range(10):
+ result = await server.read_content(locator, after=after, limit=3, no_marker=True)
+ chunks.append(result.content)
+ assert result.request_scope.page_range == "1"
+ if result.next_request is None:
+ break
+ assert result.next_request.locator == f"{_DOC_REF}/page:1"
+ locator = result.next_request.locator
+ after = result.next_request.after
+ assert after is not None
+ else:
+ pytest.fail("单页范围续读未完成")
+ assert "".join(chunks) == "abcdefghijklmnop"
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
+ "after",
+ ["doc:bbbbbbb/tier:flash/page:1/block:1", f"doc:{_SHORT_ID}/tier:basic/page:1/block:1", f"{_DOC_REF}/page:2/block:1"],
+)
+def test_range_continuation_validates_cursor_scope(tmp_path: Path, after: str) -> None:
+ """续读游标必须属于当前文档、档位和选定页面。"""
+
+ async def run() -> None:
+ """非法游标不能绕过范围选择。"""
+ db, server = await _cached_library(tmp_path)
+ try:
+ with pytest.raises(InvalidRequestError) as error:
+ await server.read_content(f"{_DOC_REF}/page:1,3", after=after)
+ assert error.value.param == "after"
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
+def test_range_http_continuation_round_trip(tmp_path: Path) -> None:
+ """HTTP 接口返回的 locator/after 可以直接再次提交并完整读完范围。"""
+
+ async def run() -> None:
+ """经真实 ASGI 路由执行两页非连续选择的字符续读。"""
+ db, server = await _cached_library(tmp_path, page_count=4)
+ try:
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=server.app), base_url="http://test") as client:
+ params: dict[str, Any] = {"locator": f"{_DOC_REF}/page:1,3", "limit": 4, "no_marker": True}
+ chunks: list[str] = []
+ for _ in range(10):
+ response = await client.get("/api/v1/content", params=params)
+ assert response.status_code == 200
+ data = response.json()
+ chunks.append(data["content"].replace("\n\n", ""))
+ if data["next_request"] is None:
+ break
+ params.update(locator=data["next_request"]["locator"], after=data["next_request"]["after"])
+ else:
+ pytest.fail("HTTP 范围续读未完成")
+ assert "".join(chunks) == "PAGE01PAGE03"
+ finally:
+ await db.close()
+
+ asyncio.run(run())
+
+
+def test_read_sdk_transmits_range_after(monkeypatch: pytest.MonkeyPatch) -> None:
+ """同步 SDK 同时传递范围定位器及绝对续读游标。"""
+ captured: list[dict[str, Any]] = []
+ locator = f"{_DOC_REF}/page:1,3"
+ after = f"{_DOC_REF}/page:1/block:1/char:4"
+
+ def send_request(self: DoclibClient, method: str, path: str, *, params: dict[str, Any], json_data: Any) -> httpx.Response:
+ """保留 SDK 构造参数的路径,只替换外部 HTTP 发送。"""
+ captured.append(params)
+ response = DocContentResponse(
+ sha256=_SHA256, short_id=_SHORT_ID, tier="flash", content="text", request_scope=ContentRequestScope(locator=locator)
+ )
+ return httpx.Response(200, request=httpx.Request(method, f"http://test{path}"), json=response.model_dump(mode="json"))
+
+ monkeypatch.setattr(DoclibClient, "_send_request", send_request)
+ client = DoclibClient(base_url="http://test")
+ try:
+ client.read_content(locator, after=after)
+ assert captured[0]["locator"] == locator
+ assert captured[0]["after"] == after
+ finally:
+ client.close()
+
+
+def test_read_cli_passes_and_renders_range_continuation(monkeypatch: pytest.MonkeyPatch) -> None:
+ """CLI 接收 --after,并在下一次命令中同时保留范围和字符游标。"""
+ locator = f"{_DOC_REF}/page:1,3"
+ after = f"{_DOC_REF}/page:1/block:1/char:4"
+ next_after = f"{_DOC_REF}/page:1/block:1/char:8"
+ calls: list[dict[str, Any]] = []
+
+ class Client:
+ """用记录器替换外部服务连接。"""
+
+ def __init__(self, *, timeout: int) -> None:
+ """内容读取沿用原有一分钟超时。"""
+ assert timeout == 60
+
+ def read_content(self, value: str, **kwargs: Any) -> DocContentResponse:
+ """返回仍在范围内部的字符续读请求。"""
+ calls.append({"locator": value, **kwargs})
+ return DocContentResponse(
+ sha256=_SHA256,
+ short_id=_SHORT_ID,
+ tier="flash",
+ content="text",
+ request_scope=ContentRequestScope(locator=value, after=after),
+ truncated=True,
+ next_request=ContentNextRequest(locator=value, after=next_after),
+ )
+
+ monkeypatch.setattr(read_commands, "DoclibClient", Client)
+ result = CliRunner().invoke(app, ["read", locator, "--after", after])
+ assert result.exit_code == 0
+ assert calls[0]["after"] == after
+ assert f"<!-- Next: mineru read {locator} --after {next_after} -->" in result.output