Skip to content

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

feat(api): process JSON tasks and deliver per-file outputs

myhloli57485941fb36
diff --git a/docs/next/api.md b/docs/next/api.md
index 5935d1f5..4bc4395e 100644
--- a/docs/next/api.md
+++ b/docs/next/api.md
@@ -22,7 +22,7 @@ Unified API 文档描述两类部署形态下的同一套 API:
3. [Health、Models 与 Tiers](api/health-models.md): 服务能力、模型列表、解析档位。
4. [Uploads 与 Files](api/uploads-files.md): 上传生命周期、文件对象、产物下载。
5. [Parse Jobs](api/parse-jobs.md): 解析任务、轮询。
- [V1 tasks](api/tasks.md): 表单清单、逐文件上传、结果 ZIP 下载链接和 Router 调度。
+ [V1 tasks](api/tasks.md): JSON 清单、逐文件上传、独立结果下载链接和 Router 调度。
6. [Chat 与 Responses](api/chat.md): OpenAI-compatible 文档对话接口。
7. [Webhooks](api/webhooks.md): 异步回调协议。
8. [Usage 与 Limits](api/usage-limits.md): access level、限流、用量查询。
diff --git a/docs/next/api/README.md b/docs/next/api/README.md
index 12366ab5..e545afb7 100644
--- a/docs/next/api/README.md
+++ b/docs/next/api/README.md
@@ -54,8 +54,8 @@ ID 使用 OpenAI 风格的前缀加随机串。官方 API 使用 24 字符 base6
| `GET` | `/v1/files/{file_id}` | 查询文件元信息 |
| `GET` | `/v1/files/{file_id}/content` | 下载解析产物 |
| `DELETE` | `/v1/files/{file_id}` | 删除文件 |
-| `POST` | `/v1/tasks` | 表单清单或本地单文件直传,返回异步任务 |
-| `GET` | `/v1/tasks/{task_id}` | 查询上传与解析状态,取得 ZIP 下载链接 |
+| `POST` | `/v1/tasks` | JSON 清单创建任务,返回缺失文件上传链接 |
+| `GET` | `/v1/tasks/{task_id}` | 查询总状态和逐文件状态,取得每个成功文件的下载链接 |
| `PUT` | 返回的上传链接 | 每个链接上传一个文件 |
| `DELETE` | `/v1/tasks/{task_id}` | 取消任务 |
| `POST` | `/v1/parse/jobs` | 创建解析任务 |
@@ -66,7 +66,7 @@ ID 使用 OpenAI 风格的前缀加随机串。官方 API 使用 24 字符 base6
| `POST` | `/v1/responses` | Responses 文档对话 |
| `GET` | `/v1/usage` | 查询用量 |
-表单、逐文件上传、结果链接与 Router 负载规则见 [V1 tasks](tasks.md)。SaaS 可以独立实现同一契约,并返回 OSS 直链;客户端不要求其实现本地 Files 下载路由。
+JSON、逐文件上传、独立结果链接与 Router 负载规则见 [V1 tasks](tasks.md)。SaaS 可以独立实现同一契约,并返回 OSS 直链;客户端不要求其实现本地 Files 下载路由。
## 认证
@@ -84,7 +84,7 @@ Local Parse Server 默认监听 loopback 且不启用鉴权。启用 `--api-key`
- 成功响应直接返回资源对象,没有外层 envelope。
- 错误响应使用 OpenAI-compatible envelope,详见 [响应与错误](responses.md)。
-- 资源级接口使用 JSON;`POST /v1/tasks` 使用表单,上传字节使用返回链接要求的内容类型。
+- 资源级接口及 `POST /v1/tasks` 使用 JSON,上传字节使用返回链接要求的内容类型。
- 时间字段按 endpoint 语义选择 ISO-8601 UTC 字符串或 Unix 秒级时间戳。
- 成功和失败响应都应携带 `X-Request-Id`。
- `Idempotency-Key` 支持属于部署能力;当前自部署 tasks 不提供创建请求幂等重试保证,恢复操作应使用原 `task_id`。
diff --git a/docs/next/api/tasks.md b/docs/next/api/tasks.md
index 57e18cf3..b51f3c11 100644
--- a/docs/next/api/tasks.md
+++ b/docs/next/api/tasks.md
@@ -1,59 +1,47 @@
-# V1 tasks:逐文件上传、URL 输入与结果下载链接
+# V1 Tasks:JSON 清单、逐文件上传与下载
-状态: Implemented(自部署 API server 与 Router)
-读者: HTTP 客户端、SaaS 接口与自部署服务开发者
+`/v1/tasks` 是本地 API Server、Router 和 SaaS 的共同异步客户端契约。
+客户端用 JSON 创建任务,按返回链接上传缺失文件,再轮询 `status_url`。
+每个文件就绪后立即执行,完成后在 `files[].result_url` 返回独立下载链接。
+客户端不拼接存储路径,也不要求 SaaS 实现本地 Files API。
-共同流程是:**提交文件清单 → 上传缺失的客户端文件 → 轮询任务 → 使用返回链接下载 ZIP**。
-清单也支持 URL 输入,由执行服务在后台下载,无需客户端提前获取文件大小或上传字节。
-SaaS 可以把上传、下载地址指向 OSS,本地服务可以指向自身的文件接口。客户端只使用服务返回的链接,不拼接存储路径,也不要求 SaaS 实现本地 Files API。
-SaaS 的 Go 服务、OSS 配置及部署由其开发方实现;这里定义客户端共同契约。
-
-## 路由与状态
+## 路由与请求
| 方法与路径 | 行为 |
|---|---|
-| `POST /v1/tasks` | 表单提交文件清单,或本地单文件 multipart 直传;返回 `202`。 |
-| 返回的 `upload_method` 与 `upload_url` | 每个链接上传一个文件,本地使用 `PUT /v1/tasks/{task_id}/uploads/{client_file_id}`。 |
-| `GET /v1/tasks/{task_id}` | 返回 `200` 和任务元数据、缺失文件上传项、可用的结果链接。 |
-| `DELETE /v1/tasks/{task_id}` | 取消等待上传或正在执行的任务。 |
-
-任务首次创建就获得稳定的 `task_id`;执行提交后,它也是当前部署的公开 `job_id`。等待上传阶段使用 tasks 查询,既有 `/v1/parse/jobs` 执行资源尚未创建。
-
-状态为 `waiting_upload`、`queued`、`running`、`completed`、`partial`、`failed`、`canceled`。
-全部客户端上传项校验通过后自动启动,不要求客户端发送完成确认。等待上传不占解析并发,也不预占 Router worker。
-纯 URL 任务直接进入 `queued`;URL 下载在后台执行阶段进行,沿用 Job 并发控制。
-`completed/partial` 只在最终 ZIP 已保存后发布;打包时仍为 `running`。`partial` 保留成功文件产物及失败文件的错误。
+| `POST /v1/tasks` | 仅接受 `application/json`,返回 `202` 和稳定 `task_id`。 |
+| 返回的 `upload_method` 与 `upload_url` | 每个链接上传一个文件;本地使用 `PUT /v1/tasks/{task_id}/uploads/{client_file_id}`。 |
+| `GET /v1/tasks/{task_id}` | 返回 `200`,包含总状态、逐文件状态、尚有效的上传链接和已完成文件的下载链接。 |
+| `DELETE /v1/tasks/{task_id}` | 取消未完成文件,保留已经完成文件的下载链接。 |
-## 表单请求
+创建请求不再接受表单、multipart 或文件字节,其他 Content-Type 返回 `415`。
+业务参数必须放在 JSON 主体中,POST 查询参数、未知字段、非法值返回 `400 invalid_request`。
+上传文件的 PUT 仍发送原始字节,使用返回的 `upload_headers`;签名 URL 必须原样使用。
+Task ID 是父任务标识,不承诺同时是 `/v1/parse/jobs` 的 Job ID。
-`POST /v1/tasks` 只接受 `application/x-www-form-urlencoded` 或 `multipart/form-data`。
-所有业务参数放在表单主体;URL 查询参数返回 `400 invalid_request`,JSON 和原始字节创建请求返回 `415`。
-文件 PUT 使用原始字节。服务返回的 OSS 签名 URL 可以包含查询串,客户端必须原样使用。
-
-| 表单字段 | 默认值 | 说明 |
+| JSON 字段 | 默认值 | 说明 |
|---|---|---|
-| `manifest` | 无 | JSON 数组形式的**文本字段**;批量任务必填,最多 100 项。 |
+| `manifest` | 必填 | 1–100 个文件组成的 JSON 数组,不接受 JSON 字符串。 |
| `tier` | 服务默认值 | `flash/basic/standard/advanced`,受部署能力约束。 |
| `ocr_mode` | `auto` | `auto/txt/ocr`。 |
-| `page_range` | 整本 | 全局 PDF 页范围;仍支持 `1-5`、`r1`、`all` 等现有语法。 |
-| `output_formats` | `markdown` | 可重复字段,支持 `markdown/middle_json/structured_content/zip`;最终 ZIP 始终生成。 |
-| `files` | 无 | 仅本地单文件 multipart 直传使用,最多一个文件。 |
+| `page_range` | 整本 | 全局 PDF 页范围,支持 `1-5`、`r1`、`all` 等现有语法。 |
+| `output_formats` | `["default"]` | 非空列表,值为 `default/docx/html/latex` 中一个或多个;重复值按首次出现去重。 |
每个清单条目包含:
| 字段 | 必填 | 说明 |
|---|---|---|
-| `client_file_id` | 是 | 一次任务内唯一,1–64 个字母、数字、下划线或短横线。 |
+| `client_file_id` | 是 | 任务内唯一,1–64 个字母、数字、下划线或短横线。 |
| `filename` | 是 | 逻辑文件名,保留扩展名;不同条目允许同名。 |
-| `url` | 否 | 文件下载地址,支持 HTTP(S),具体协议受部署策略约束;省略或 `null` 表示客户端上传。 |
-| `bytes` | 条件 | 上传项必填;URL 项可省略或为 `null`。提供时必须为严格正整数,用于核对实际字节数。 |
-| `sha256sum` | 否 | 64 位小写十六进制 SHA-256;上传项用于缓存预检与完整性校验,URL 项仅用于下载完整性校验。 |
-| `page_range` | 否 | 逐文件页范围,未提供时继承全局值;非 PDF 仍只支持整本解析。 |
+| `url` | 否 | HTTP(S) 文件下载地址,受部署来源策略约束;省略或 `null` 表示客户端上传。 |
+| `bytes` | 条件 | 上传项必填;URL 项可省略或为 `null`。提供时必须是严格正整数。 |
+| `sha256sum` | 否 | 64 位小写十六进制 SHA-256;用于完整性校验,上传项还用于源文件缓存预检。 |
+| `page_range` | 否 | 逐文件 PDF 页范围,未提供时继承全局值;非 PDF 仍只支持整本解析。 |
-用真实文件生成清单,再发送表单:
+先从真实文件生成 JSON 请求:
```bash
-python3 - a.pdf b.pdf > manifest.json <<'PY'
+python3 - a.pdf b.pdf > task.json <<'PY'
import hashlib
import json
from pathlib import Path
@@ -72,158 +60,166 @@ for index, value in enumerate(sys.argv[1:], start=1):
'bytes': path.stat().st_size,
'sha256sum': hasher.hexdigest(),
})
-print(json.dumps(manifest, ensure_ascii=False))
+print(json.dumps({'manifest': manifest, 'tier': 'flash', 'ocr_mode': 'txt',
+ 'output_formats': ['default', 'latex']}, ensure_ascii=False))
PY
curl --fail-with-body "$MINERU_API_URL/v1/tasks" \
-H "Authorization: Bearer $MINERU_API_KEY" \
- --data-urlencode 'tier=flash' \
- --data-urlencode 'ocr_mode=txt' \
- --data-urlencode '[email protected]'
+ -H 'Content-Type: application/json' \
+ --data-binary @task.json
```
-匿名本地服务可省略 Authorization。无需 hash 时从清单中省略 `sha256sum`。
-`client_file_id` 用于关联文件和上传项,不能按文件名判断对应关系。
+未配置 API Key 的本地服务可省略 Authorization,四种输出格式均可用;启用服务认证后四种格式均需认证,没有额外的格式权限限制。
-## URL 提交与混合输入
+## URL、缓存与独立上传
-```bash
-curl --fail-with-body "$MINERU_API_URL/v1/tasks" \
- -H "Authorization: Bearer $MINERU_API_KEY" \
- --data-urlencode 'tier=flash' \
- --data-urlencode 'ocr_mode=txt' \
- --data-urlencode 'manifest=[{"client_file_id":"f1","filename":"document.pdf","url":"https://example.com/download?signature=example"}]'
-```
+URL 输入同样先创建 JSON 任务:
-`filename` 仍然必填,用于文件类型识别、展示和产物命名,不要求 URL 路径有扩展名。
-URL 项的 `upload_status` 为 `not_required`,不产生上传链接,也不接受 PUT;源 `file_id` 为 `null`。
-未声明的 `bytes` 在下载前为 `null`,完整下载并校验通过后返回实际大小及 SHA-256。
-声明的大小或 hash 不匹配时,该文件失败,不进入解析;空文件同样失败。
+```json
+{
+ "manifest": [
+ {"client_file_id": "remote", "filename": "document.pdf", "url": "https://example.com/download?signature=example"},
+ {"client_file_id": "local", "filename": "other.pdf", "bytes": 12345}
+ ],
+ "output_formats": ["html"]
+}
+```
-同一 manifest 可以混合 URL 与上传项,`uploads` 仅包含需要客户端上传的条目。
-混合任务在这些上传完成后进入执行阶段,URL 下载不需要客户端参与。URL 与 multipart 字节不能同时指定给同一项。
-URL 每次重新下载,即使声明的 hash 已在源文件缓存中,也不跳过下载;不要求 HEAD 或 `Content-Length`。
+- URL 项的 `upload_status` 为 `not_required`,不生成上传链接、不接受 PUT;源 `file_id` 为 `null`。创建后即进入执行队列,不等待其他上传。
+- URL 保留原始签名地址,使用逻辑 `filename` 识别类型;不要求 HEAD 或 `Content-Length`。下载后返回实际 `bytes` 和 `sha256sum`,提供的大小/hash 必须匹配。URL 每次下载,不用 hash 缓存跳过下载。
+- 上传项 hash 命中时为 `ready`,不返回上传链接,立即排队;未命中或无 hash 时返回该文件的链接。上传后仍计算 hash、校验大小并对源字节去重。
+- 缓存只复用源文件,不复用不匹配的解析结果;每个文件使用本次解析参数独立执行。
+- 每个上传项校验完成即排队,不需要客户端发送完成确认。等待上传不占解析并发,也不预占 worker。
-下载失败、超时或完整性校验失败按文件记录错误,其他文件继续执行;有成功项则返回 `partial` 和 ZIP,全部失败则为 `failed` 且无 `result_url`。
-URL 大小不一致使用 `bytes_mismatch`,hash 不一致使用 `file_hash_mismatch`。请求格式和部署策略错误仍按接单校验处理。
+### 一小时上传窗口
-## 缓存、上传与恢复
+所有上传链接的 `expires_at` 固定为创建时起 3600 秒,采用 Unix 秒。查询不会延长或换发链接。
+到期后新 PUT 返回 `410 upload_expired`,包括对已经确认文件的重复 PUT。
-以下缓存规则适用于无 `url` 的客户端上传项:
+截止前已受理的上传可以继续传完并校验,该文件仍处于 `waiting_upload`,不会被过期扫描中止。
+尚未受理上传的文件到期后变为 `status=failed`、`upload_status=expired`,逐文件错误码为 `upload_expired`。
+在途上传中断且已经过期时,同样进入失败终态;补交须创建新任务。
+上传截止时间不限制已上传文件的排队、解析或导出时间。
-- 全部 hash 命中:返回空 `uploads`,直接提交解析。
-- 部分命中:仅返回未命中文件的上传项,命中文件已经是 `ready`。
-- 无 hash 或未命中:上传完整文件;服务端计算实际 hash、校验大小与可选 hash,并去重保存。
+有效期内,一个文件中断或校验失败可以从头重传,其他文件的状态不受影响。
+重复 PUT 已确认文件不读取或覆盖源字节,并发请求也只提交一次解析。
+上传响应丢失时先查询:已经 `ready` 则跳过;仍待上传且链接有效时再重试。
+不支持单文件分块断点续传。
-缓存是**源文件缓存**,本次解析仍使用本次 tier、页范围和其他参数。
-新请求不会凭文件 hash 复用不匹配的解析结果。
+## 总状态与逐文件状态
-响应中的共同字段:
+状态响应只有元数据,不内联 Markdown、JSON 或结果文件字节。
+`files` 按原清单顺序返回,使用 `client_file_id` 对应输入,不依赖文件名唯一性。
| 字段 | 说明 |
|---|---|
-| `task_id`、`status`、`status_url` | 稳定任务 ID、当前状态和查询地址。 |
-| `files` | 按输入顺序返回清单、`upload_status: pending/ready/not_required`、逐文件解析状态及错误;URL 项始终为 `not_required`。 |
-| `uploads` | 尚需上传的文件,每项包含 `client_file_id`、`upload_url`、`upload_method: PUT`、`upload_headers`、`expires_at`。 |
-| `result_url` | 结果未就绪时为 `null`;`completed/partial` 时为最终 ZIP 下载地址。 |
-| `error` | 任务级错误,例如上传过期或结果打包失败。 |
+| `task_id`、`status`、`status_url` | 稳定父任务标识、聚合状态、查询地址。 |
+| `files[].upload_status` | `pending/ready/not_required/expired`。 |
+| `files[].status` | `waiting_upload/queued/running/completed/failed/canceled`,包含导出过程。 |
+| `files[].result_url` | 该文件产物完整保存前为 `null`;`completed` 时为唯一下载链接。 |
+| `files[].error` | 该文件的上传过期、下载、解析或导出错误。 |
+| `uploads` | 仍有效的待上传项:`client_file_id/upload_url/upload_method/upload_headers/expires_at`。 |
+| `progress` | 文件计数:`completed/failed/total`,`total` 固定为清单长度;取消不计为解析失败。 |
+| `error` | 父任务级错误;逐文件错误应读取 `files[].error`。 |
-本地上传准备默认有效期为 3600 秒,链接的 `expires_at` 为 Unix 秒。
-一个文件完整校验后才变为 `ready`;中断内容不会进入解析或缓存。
-已成功的文件独立保留,后续文件中断只需重传失败文件,继续使用原 `task_id`。
-重复 PUT 已确认文件不会覆盖源字节;同时完成多个文件只会触发一次解析。
+Task 顶层没有 `result_url`;`files[]` 不暴露底层 `output_files`。
+已完成文件可以在父任务仍为 `running/queued/waiting_upload` 时下载。
-本轮提供文件级重试,单个文件失败后从头重传,不支持分块断点续传。
-上传响应丢失时先查询任务:文件已 `ready` 就跳过,否则重试该项。
-链接过期而任务仍有效时,重新查询同一任务获取当前链接;本地准备任务整体过期后返回 `failed/upload_expired`。
+总状态优先级如下:
-## 本地单文件快捷直传
+| 条件 | `status` |
+|---|---|
+| 存在运行中的文件,包括导出阶段 | `running` |
+| 没有运行文件,存在排队文件 | `queued` |
+| 剩余未完成文件全部等待上传 | `waiting_upload` |
+| 所有文件成功 | `completed` |
+| 所有文件终结,成功与失败并存 | `partial` |
+| 所有文件终结,无成功文件 | `failed` |
+| 用户取消任务 | `canceled` |
-```bash
-curl --fail-with-body "$MINERU_API_URL/v1/tasks" \
- -H "Authorization: Bearer $MINERU_API_KEY" \
- -F 'tier=flash' \
- -F 'ocr_mode=txt' \
-```
+因此,第一个文件解析完成而第二个文件尚未上传时,总状态可以由 `running` 回到 `waiting_upload`,第一个文件的下载链接仍然有效。
+取消只停止未完成的文件,已经成功或失败的文件保持原状态;重复取消终态任务返回 `409`。
-返回异步任务,不保持连接等待解析。需要声明 hash 时,同时提交仅含一个条目的 manifest 文本字段,例如 `-F 'manifest=<single-manifest.json'`。
+## 输出格式与下载
-多个文件字段,或者多文件清单混入文件字节,返回 `400`,应改用逐文件上传链接。
-直传时实际发送的字节全部接受完整性校验;它不承诺在 hash 命中时跳过网络传输。稳定的省流量由清单预检提供。
+一个输入文件对应一个下载链接,与该 Task 有多少输入文件无关。
-## 下载结果
+| `output_formats` | 下载内容 |
+|---|---|
+| `["default"]` | ZIP:`markdown.md`、`middle_json.json`、`structured_content.json`、`images/`。 |
+| `["docx"]` | 图片内嵌的单个 `.docx`。 |
+| `["html"]` | 图片内嵌的单个 `.html`。 |
+| `["latex"]` | ZIP:`document.tex`、`images/`。 |
+| 多个不同值 | 一个 ZIP,平铺对应文件,不嵌套 ZIP。 |
-轮询只访问响应的 `status_url`。状态接口不内联 Markdown、Middle JSON 或 ZIP 内容。
+多格式 ZIP 内 DOCX 和 HTML 分别为 `document.docx`、`document.html`。
+`default` 和 LaTeX 共用同一套物化图片及 `images/` 引用;无图片时目录可为空。
+DOCX 和 HTML 即使放入多格式 ZIP,也保持图片内嵌。
+`default` 不自动包含 `model_output.json`;不生成跨输入文件的总 ZIP 或批次 `manifest.json`。
-- SaaS 返回 OSS 签名下载地址,客户端直接从 OSS 下载,结果字节不经过 API 网关。
-- 本地返回 `/v1/files/{file_id}/content` 的完整地址,服务端从已保存文件流式输出。
-- Router 返回自身的 Files 地址并流式代理 worker 产物,不泄露内部 worker 地址。
+每个输入只解析一次,基于同一结果生成所选格式。全部所选格式完成并保存后才发布该文件的 `completed` 和链接。
+任一格式失败,该文件为 `failed/result_packaging_failed` 且链接为空,不提供不完整产物;其他文件继续执行。
+导出复用已物化素材,不重新打开源文件或修改原语义树。图片缺失时报错,不交付引用失效的 HTML 单文件。
+HTML 的“单文件”保证图片内嵌,公式脚本仍沿用现有 renderer 的行为。
-所有 tasks 自动生成 ZIP;单文件保留现有自包含产物,批量使用 `0001/`、`0002/` 等目录并包含 `manifest.json`。
-manifest 使用 `client_file_id` 关联输入,`directory` 指向包内目录,不写入 worker 的私有 task/file ID 或短期下载链接,也不写入源 `url` 字段。已校验的 URL 输入记录实际大小与 hash。任务 ID 以 HTTP 响应为准。
-ZIP 在后台只生成一次;重复查询或下载不重新打包。打包失败返回 `failed/result_packaging_failed`,不会发布虚假的下载链接。
-签名链接过期但产物仍在保留期内时,重新查询任务获得有效地址,不重新提交解析。
+- SaaS 返回对象存储签名地址,结果字节不经过网关。
+- 本地返回 `/v1/files/{file_id}/content` 的完整地址,流式输出已保存产物。
+- Router 映射自身 Files 地址并流式代理 worker,不暴露内部 worker 地址。
-认证只附加到与 API 同源的请求。同源由协议、主机、有效端口共同决定;OSS、外部下载地址及跨源重定向不附加 MinerU API Key。
-上传额外请求头使用 `upload_headers`,不硬编码云存储 SDK 或 OSS 域名。
+轮询及重复下载不重新渲染或打包。下载签名过期时,可在结果保留期内再次查询任务取得有效地址;这与不可续期的上传链接不同。
+已经完成的结果不会因为其他文件仍在等待而提前回收,保留期从父 Task 清理完成后开始。
+认证只附加到 API 同源请求;对象存储及跨源重定向不得携带 MinerU API Key。
-## 完整客户端示例
+## 客户端示例
-`scripts/http_task_example.sh` 调用同目录的 `http_task_example.py`,只需要 Python 3.10+ 标准库,无需安装 MinerU 或云存储 SDK。
-该脚本接受本地文件路径;URL 提交使用上面的 curl 示例。
-默认顺序上传,每个文件最多尝试三次,仅重试网络及临时服务错误;创建请求不自动重试。
-脚本校验任务身份、状态和文件对应关系,轮询有预算,下载先写临时文件并验证 ZIP 后再保存最终文件。
+`scripts/http_task_example.sh` 调用同目录 Python 脚本,仅需要 Python 3.10+ 标准库。
+创建请求不会自动重试;文件传输有界重试,先查询状态再处理响应丢失。
+下载使用临时文件、验证对应格式后原子保存,成功文件保存在 `RESULT_DIR/<client_file_id>/<输入文件主名>.<扩展名>`。
```bash
MINERU_API_URL=http://127.0.0.1:8000 \
bash scripts/http_task_example.sh a.pdf b.pdf
-SEND_HASH=0 MINERU_API_URL=http://127.0.0.1:8000 \
+OUTPUT_FORMATS=default,latex,docx RESULT_DIR=results \
+MINERU_API_URL=http://127.0.0.1:8000 \
bash scripts/http_task_example.sh a.pdf b.pdf
-# 恢复时使用首次提交的文件列表和顺序,不重新创建任务。
+# 使用首次提交的文件列表和顺序恢复,不重新创建任务。
TASK_ID=job_... MINERU_API_URL=http://127.0.0.1:8000 \
bash scripts/http_task_example.sh a.pdf b.pdf
-
-UPLOAD_MODE=direct MINERU_API_URL=http://127.0.0.1:8000 \
- bash scripts/http_task_example.sh a.pdf
```
| 配置 | 默认值 | 说明 |
|---|---|---|
| `MINERU_API_URL` | 必填 | API 或 Router 基地址。 |
-| `MINERU_API_KEY` | 空 | API 认证,匿名本地服务可省略。 |
-| `UPLOAD_MODE` | `preflight` | `preflight/direct`,direct 只支持一个文件。 |
+| `MINERU_API_KEY` | 空 | 服务认证。 |
| `SEND_HASH` | `1` | `0` 时不计算或提交 hash。 |
-| `TASK_ID` | 空 | 继续已有任务,按原文件列表跳过 ready 文件。 |
+| `TASK_ID` | 空 | 恢复已有任务,跳过 ready 文件。 |
| `MINERU_TIER`、`OCR_MODE`、`PAGE_RANGE` | 服务默认 / `auto` / 整本 | 解析参数。 |
-| `OUTPUT_FORMATS` | `markdown` | 逗号分隔,自动加入 ZIP。 |
-| `RESULT_FILE` | `result.zip` | 最终文件位置。 |
-| `MAX_POLLS`、`POLL_INTERVAL` | `300`、`1` | 最多查询次数与间隔秒数。 |
-| `CONNECT_TIMEOUT`、`REQUEST_TIMEOUT` | `10`、`600` | 连接和单次传输超时秒数。 |
-| `MINERU_PYTHON` | `python3` | 可指定 Python 可执行文件。 |
-
-退出码为 `0`(全部成功且保存 ZIP)、`2`(部分成功且保存 ZIP)、`1`(失败或取消)、`124`(轮询预算耗尽)。
-取得任务 ID 后发生错误会打印恢复方式;轮询超时不会取消任务。
-
-## 本地限制与 Router 调度
-
-本地不设固定客户端上传字节数或 PDF 页数上限;`usage.limits.max_file_size_bytes` 与 `max_pages_per_file` 为 `null`。
-每任务最多 100 文件。URL 下载沿用 Jobs 的配置:默认只允许 HTTPS,HTTP 需启用 `--allow-http-source`,超时由 `--url-timeout` 控制(默认 60 秒),大小由 `--max-url-bytes` 控制(默认 200 MiB)。这些预算不要求客户端提前声明 `bytes`。
-既有 Jobs 的 inline 来源预算仍按其专用配置生效。
-源文件、上传索引和任务记录仍是进程内状态,重启不保证恢复;完成后的任务及产物沿用部署的保留策略。
-
-Router 的 tasks 与 V1 Uploads 复用按调用方隔离的源字节缓存。
-全部客户端上传项齐备后才选择并预占 worker,再向该 worker 提交 tasks 和传输其缺失文件。
-URL 原样交给支持该来源的 worker 下载,Router 不下载源 URL;URL 下载策略由 worker 配置决定。
-worker 负责最终 ZIP,Router 只查询任务与 File 元数据并映射公开下载地址。
-同负载轮询,缓存命中不把任务固定到繁忙 worker;一个批量任务仍交给同一个 worker。
-失败、取消、终态和后台回收通过同一机制释放预占,等待上传不计入执行负载。
-
-## 迁移
-
-旧 `/v1/file_parse` 和 `/v1/tasks/{task_id}/result` 已移除;不提供同步等待 HTTP 路由或结果正文路由。
-客户端改为轮询 `status_url` 并下载 `result_url`,删除旧 `MODE=sync`、`RESPONSE_FORMAT`、`wait_timeout` 配置。
-旧 tasks JSON 来源、原始字节创建请求和 POST 查询参数不再接受;URL 可通过 tasks 表单 manifest 提交。inline、local、file_id 等资源来源继续使用既有 `/v1/parse/jobs` 协议。
-独立 `/v1/uploads` 与 `/v1/parse/jobs` 的 JSON 请求协议保持不变。
+| `OUTPUT_FORMATS` | `default` | 逗号分隔,转为 JSON 数组。 |
+| `RESULT_DIR` | `results` | 逐文件结果目录。 |
+| `MAX_POLLS`、`POLL_INTERVAL` | `300`、`1` | 查询预算和间隔秒数。 |
+| `CONNECT_TIMEOUT`、`REQUEST_TIMEOUT` | `10`、`600` | 连接与单次传输超时秒数。 |
+| `MINERU_PYTHON` | `python3` | Python 可执行文件。 |
+
+退出码为 `0`(全部成功)、`2`(部分成功)、`1`(失败或取消)、`124`(轮询预算耗尽)。已下载的成功结果保留。
+轮询超时不取消服务端任务。`UPLOAD_MODE` 与 `RESULT_FILE` 已删除。
+
+## 部署、Router 与迁移
+
+本地不设固定客户端上传大小或 PDF 页数上限;`usage.limits.max_file_size_bytes/max_pages_per_file` 为 `null`。
+URL 下载沿用 Jobs 的策略:默认 HTTPS;HTTP 需启用 `--allow-http-source`,下载超时默认 60 秒、大小默认 200 MiB。
+任务记录和上传索引仍为进程内状态,重启不保证恢复。
+
+Router 按就绪文件独立选择 worker 并预占负载,同一父 Task 可使用多个 worker。
+URL 交给 worker 下载,客户端上传字节按 worker 的缓存预检结果传输。
+健康接口的 `features.task_output_formats` 单独声明 Tasks 格式;原 `features.output_formats` 继续描述 Jobs。
+不声明新 Tasks 能力的旧 worker 不参与 Tasks 调度,更新时应先更新 worker,再更新 Router 和客户端。
+Router 使用有界、可续租的内部结果租约保护 worker 产物,上传窗口不受结果租约影响;Router 丢失后租约会自行结束。
+
+本次协议不保留旧表单、直传或 `markdown/middle_json/structured_content/zip` Tasks 格式别名。
+客户端应改用 JSON、`files[].result_url` 及逐文件保存方式。
+独立 `/v1/uploads`、`/v1/parse/jobs` 与 SDK 的现有请求及输出协议保持不变。
+`/v1/file_parse`、`/v1/tasks/{task_id}/result` 不恢复。
+SaaS Go 服务和对象存储配置由部署方按此共同契约实现,不属于本地 Python 服务代码。
diff --git a/docs/next/cli/mineru-kit.md b/docs/next/cli/mineru-kit.md
index 6da86f82..4d0dee53 100644
--- a/docs/next/cli/mineru-kit.md
+++ b/docs/next/cli/mineru-kit.md
@@ -90,6 +90,6 @@ mineru-api --host 127.0.0.1 --port 8000 --tier standard
- `--upstream-url` 可重复,用于接入已有 MinerU V1 API base URL。
- `--local-gpus` 支持 `auto`、`none` 或 GPU CSV,例如 `0,1,2`。
- 本地 worker 统一启动 `mineru-kit api-server`;`--worker-tier` 默认 `standard`,`--worker-concurrency` 默认 `1`。
-- Router 完整代理 V1 health、models、tiers、uploads、files、parse jobs 与 usage,并提供 `/v1/tasks` 表单任务、逐文件上传及结果下载链接;不提供旧根路径。
+- Router 完整代理 V1 health、models、tiers、uploads、files、parse jobs 与 usage,并提供 `/v1/tasks` JSON 任务、逐文件上传和执行及独立结果下载链接;不提供旧根路径。
- Router 只接受显式声明的参数,不再透传未知模型引擎参数;需要额外调优时应部署独立 upstream。
- uploads、files 与 jobs 的公共路由状态保存在当前进程内,Router 重启后不保证旧公共 ID 继续可用。
diff --git a/mineru/kit/router/app.py b/mineru/kit/router/app.py
index 2d8e1e34..eca36fb2 100644
--- a/mineru/kit/router/app.py
+++ b/mineru/kit/router/app.py
@@ -322,7 +322,8 @@ async def _finalize_terminal_job(
route.metadata["copied_inputs"] = pending
else:
route.metadata.pop("copied_inputs", None)
- route.metadata.pop("upstream_headers", None)
+ if not route.metadata.get("task_result_held"):
+ route.metadata.pop("upstream_headers", None)
route.metadata.setdefault("finalized_at", utc_now_iso())
@@ -458,6 +459,15 @@ def create_app(
application.state.started_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
reconcile_task: asyncio.Task[None] | None = None
collection_task: asyncio.Task[None] | None = None
+ lease_task: asyncio.Task[None] | None = None
+
+ async def task_lease_loop() -> None:
+ """独立维护 Tasks 的结果租约,禁用 worker 刷新时也保证下载保留期。"""
+ from .tasks import maintain_task_result_leases
+
+ while True:
+ await asyncio.sleep(30)
+ await maintain_task_result_leases(registry, pool)
async def collection_loop() -> None:
"""每五分钟同步回收过期公共路由与无引用源文件缓存。"""
@@ -470,6 +480,7 @@ def create_app(
collection_task = asyncio.create_task(collection_loop(), name="mineru-router-retention")
await pool.start()
task_store.start()
+ lease_task = asyncio.create_task(task_lease_loop(), name="mineru-router-task-result-leases")
if resolved_settings.worker_refresh_interval_seconds > 0:
reconcile_task = asyncio.create_task(
_job_reconcile_loop(
@@ -491,6 +502,12 @@ def create_app(
except asyncio.CancelledError:
pass
await task_store.shutdown()
+ if lease_task is not None:
+ lease_task.cancel()
+ await asyncio.gather(lease_task, return_exceptions=True)
+ from .tasks import maintain_task_result_leases
+
+ await maintain_task_result_leases(registry, pool, release=True)
await pool.close()
source_store.close()
@@ -527,11 +544,19 @@ def create_app(
output_formats = sorted(
{output_format for worker in workers for output_format in worker.features.get("output_formats") or []}
)
+ task_output_formats = sorted(
+ {output_format for worker in workers for output_format in worker.features.get("task_output_formats") or []}
+ )
return JSONResponse(
{
"status": "ok",
"version": __version__,
- "features": {"webhook": False, "output_formats": output_formats, "sources": sources},
+ "features": {
+ "webhook": False,
+ "output_formats": output_formats,
+ "task_output_formats": task_output_formats,
+ "sources": sources,
+ },
}
)
diff --git a/mineru/kit/router/resources.py b/mineru/kit/router/resources.py
index d34aef55..cd10d06f 100644
--- a/mineru/kit/router/resources.py
+++ b/mineru/kit/router/resources.py
@@ -289,6 +289,9 @@ class ResourceRegistry:
def is_expired(self, route: ResourceRoute) -> bool:
"""优先沿用上游显式期限;任务从清理完成时间开始计算保留期限。"""
+ if route.metadata.get("task_result_held"):
+ until = route.metadata.get("task_result_retain_until")
+ return until is not None and until <= time.time()
payload = route.metadata.get("payload") or {}
if route.kind == "job":
if payload.get("status") not in {"completed", "partial", "failed", "canceled"}:
@@ -328,6 +331,7 @@ class ResourceRegistry:
or public_id in protected
or route.metadata.get("copied_inputs")
or route.metadata.get("pins")
+ or route.metadata.get("task_result_held")
):
continue
self.remove(kind, public_id)
diff --git a/mineru/kit/router/tasks.py b/mineru/kit/router/tasks.py
index ed776419..12230e19 100644
--- a/mineru/kit/router/tasks.py
+++ b/mineru/kit/router/tasks.py
@@ -1,17 +1,16 @@
-"""Router 的逐文件任务适配器;worker 负责解析与最终 ZIP,Router 仅映射资源。"""
+"""Router 的逐文件任务适配器;worker 负责解析与单文件产物,Router 仅映射资源。"""
from __future__ import annotations
import asyncio
import copy
-import json
import secrets
import time
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
from contextlib import ExitStack
from dataclasses import replace
from typing import Any
-from urllib.parse import SplitResult, quote, unquote, urlencode, urljoin, urlsplit
+from urllib.parse import SplitResult, quote, unquote, urljoin, urlsplit
import httpx
from fastapi import FastAPI, Request
@@ -84,11 +83,14 @@ async def _worker_request(
*,
request: Request | None = None,
content: bytes | AsyncIterator[bytes] | None = None,
+ json_body: dict[str, Any] | None = None,
headers: Mapping[str, str] | None = None,
) -> httpx.Response:
"""把网络错误转换成共享 tasks 错误,监控阶段可识别临时失败并继续查询。"""
try:
- return await request_upstream(pool, worker, method, path, request=request, content=content, headers=headers)
+ return await request_upstream(
+ pool, worker, method, path, request=request, content=content, json_body=json_body, headers=headers
+ )
except RouterProxyError as exc:
_raise_api_error(exc.status_code, error_type="api_error", code=exc.code, message=exc.message, param=exc.param)
@@ -124,7 +126,7 @@ def _job_payload(payload: dict[str, Any], upstream_id: str, *, authenticated: bo
"started_at": payload.get("started_at"),
"finished_at": payload.get("finished_at"),
"tier": payload["tier"],
- "output_formats": payload["output_formats"],
+ "output_formats": [],
"progress": payload["progress"],
"access_level": "registered" if authenticated else "anonymous",
"files": files,
@@ -153,7 +155,7 @@ async def read_task_execution(
request: Request | None = None,
headers: Mapping[str, str] | None = None,
) -> TaskExecution:
- """查询 worker 的轻量任务状态,并把最终 ZIP 登记为 Router 的公共 File。"""
+ """查询 worker 的轻量任务状态,并把单文件产物登记为 Router 的公共 File。"""
if route.metadata.get("upstream_lost"):
return _lost_execution(route, pool)
worker = pool.get(route.worker_id)
@@ -164,7 +166,10 @@ async def read_task_execution(
"GET",
f"/v1/tasks/{quote(route.upstream_id, safe='')}",
request=request,
- headers=headers,
+ headers={
+ **(headers or {}),
+ **({"x-mineru-task-lease-seconds": "120"} if route.metadata.get("task_result_held") else {}),
+ },
)
if response.status_code == 404 or worker.generation != generation or route.metadata.get("upstream_lost"):
return _lost_execution(route, pool)
@@ -175,14 +180,16 @@ async def read_task_execution(
if payload["task_id"] != route.upstream_id:
_raise_api_error(502, error_type="api_error", code="invalid_upstream_response", message="Upstream task ID changed")
result_file_id: str | None = None
- if payload["status"] in {"completed", "partial"}:
- result_url = payload.get("result_url")
+ if len(payload["files"]) != 1:
+ _raise_api_error(502, error_type="api_error", code="invalid_upstream_response", message="Expected one task file")
+ if payload["files"][0]["status"] == "completed":
+ result_url = payload["files"][0].get("result_url")
if not isinstance(result_url, str):
- _raise_api_error(502, error_type="api_error", code="invalid_upstream_response", message="Missing ZIP URL")
+ _raise_api_error(502, error_type="api_error", code="invalid_upstream_response", message="Missing result URL")
path = _worker_path(worker, result_url)
parts = path.strip("/").split("/")
if len(parts) != 4 or parts[:2] != ["v1", "files"] or parts[-1] != "content":
- _raise_api_error(502, error_type="api_error", code="invalid_upstream_response", message="Invalid ZIP File URL")
+ _raise_api_error(502, error_type="api_error", code="invalid_upstream_response", message="Invalid result File URL")
upstream_file_id = unquote(parts[2])
existing = registry.find_upstream("file", route.owner_scope, worker.worker_id, upstream_file_id)
if existing is None or not isinstance(existing.metadata.get("payload"), dict):
@@ -199,11 +206,14 @@ async def read_task_execution(
require_worker_generation(worker, generation)
if metadata.get("id") != upstream_file_id or metadata.get("purpose") != "parse_output":
_raise_api_error(
- 502, error_type="api_error", code="invalid_upstream_response", message="Invalid ZIP File metadata"
+ 502, error_type="api_error", code="invalid_upstream_response", message="Invalid result File metadata"
)
result_file_id = rewrite_file_payload(metadata, worker, registry, route.owner_scope)["id"]
else:
result_file_id = existing.public_id
+ result_route = registry.find("file", result_file_id)
+ if result_route is not None:
+ result_route.metadata["task_result_held"] = bool(route.metadata.get("task_result_held"))
authenticated = bool(request.headers.get("authorization") if request is not None else (headers or {}).get("authorization"))
rewritten = rewrite_job_payload(
_job_payload(payload, route.upstream_id, authenticated=authenticated),
@@ -227,7 +237,7 @@ class RouterTaskBackend:
"""客户端上传项就绪后才选择 worker;URL 原样交由 worker 下载。"""
def __init__(self, request: Request, owner_scope: str, finalize: FinalizeJob) -> None:
- """保存轻量上下文与显式收尾回调,不跨请求保存上传表单。"""
+ """保存轻量上下文与显式收尾回调,不跨请求保存上传主体。"""
self.request = Request(dict(request.scope))
self.owner_scope = owner_scope
self.finalize = finalize
@@ -237,26 +247,51 @@ class RouterTaskBackend:
self._pins = ExitStack()
self._owned_files: list[str] = []
+ def fork(self) -> RouterTaskBackend:
+ """每个输入文件拥有独立暂存引用和 worker 调度上下文。"""
+ return RouterTaskBackend(self.request, self.owner_scope, self.finalize)
+
+ async def release_result(self, task_id: str, finished: float) -> None:
+ """父任务完成后记录公开保留期限,后台续租直到该期限再释放 worker。"""
+ route = self.registry.find("job", task_id)
+ if route is None:
+ return
+ route.metadata["task_result_retain_until"] = (
+ finished + self.registry.retention_seconds if self.registry.retention_seconds else None
+ )
+ route.metadata["finalized_at"] = utc_now_iso()
+ result_id = route.metadata.get("task_result_file_id")
+ result_route = self.registry.find("file", result_id) if result_id else None
+ if result_route is not None:
+ result_route.metadata["payload"]["expires_at"] = route.metadata["task_result_retain_until"]
+ result_route.metadata["task_result_retain_until"] = route.metadata["task_result_retain_until"]
+
async def validate(self, options: UploadTaskOptions, manifest: list[TaskManifestItem]) -> None:
"""能力预检不推进轮询游标,也不为尚未上传的任务预占 worker。"""
tiers = self.pool.available_tiers()
options.tier = resolve_task_tier(options, manifest, tiers, select_default_quality_tier(tiers))
- lightweight = [is_flash_only_parse_extension(item.filename) for item in manifest]
- selection_tier = "flash" if all(lightweight) and options.tier not in tiers else options.tier
- candidates = self.pool.capable_workers(
- tier=selection_tier,
- required_sources={"url" if item.url is not None else "file_id" for item in manifest},
- required_outputs=set(options.output_formats),
- require_flash=any(lightweight),
- )
- if not candidates:
- _raise_api_error(
- 503, error_type="api_error", code="quality_tier_unavailable", message="No worker supports requested formats"
+ checked_workers: set[str] = set()
+ for item in manifest:
+ lightweight = is_flash_only_parse_extension(item.filename)
+ selection_tier = "flash" if lightweight else options.tier
+ candidates = self.pool.capable_workers(
+ tier=selection_tier,
+ required_sources={"url" if item.url is not None else "file_id"},
+ required_task_outputs=set(options.output_formats),
+ require_flash=lightweight,
)
-
- # 沿用 worker 的认证边界;只读检查不推进调度游标,也不预占解析容量。
- worker = candidates[0]
- _checked_json(await _worker_request(self.pool, worker, "GET", "/v1/files?limit=1", request=self.request))
+ if not candidates:
+ _raise_api_error(
+ 503,
+ error_type="api_error",
+ code="quality_tier_unavailable",
+ message="No worker supports requested task formats",
+ )
+ # 能力预检不预占名额,不推进轮询游标;认证沿用所选部署的服务认证。
+ worker = candidates[0]
+ if worker.worker_id not in checked_workers:
+ _checked_json(await _worker_request(self.pool, worker, "GET", "/v1/files?limit=1", request=self.request))
+ checked_workers.add(worker.worker_id)
async def find_upload(self, sha256sum: str, filename: str) -> TaskUpload | None:
"""仅复用当前调用方持有的 Router 源字节,worker 哈希命中不能替代本地缓存。"""
@@ -296,11 +331,11 @@ class RouterTaskBackend:
) -> TaskExecution:
"""预占后提交 worker 任务,只向 worker 上传它实际缺失的文件。"""
lightweight = all(is_flash_only_parse_extension(item.filename) for item in manifest)
- tier = "flash" if lightweight and options.tier not in self.pool.available_tiers() else options.tier
+ tier = "flash" if lightweight else options.tier
reservation = self.pool.reserve_job(
tier=tier,
required_sources={"url" if item.url is not None else "file_id" for item in manifest},
- required_outputs=set(options.output_formats),
+ required_task_outputs=set(options.output_formats),
require_flash=any(is_flash_only_parse_extension(item.filename) for item in manifest),
)
if reservation is None:
@@ -319,16 +354,19 @@ class RouterTaskBackend:
else {**item.model_dump(exclude_none=True), "sha256sum": uploads[index].sha256sum}
for index, item in enumerate(manifest)
]
- form = [("manifest", json.dumps(worker_manifest)), ("tier", options.tier), ("ocr_mode", options.ocr_mode)]
- form.extend(("output_formats", value) for value in options.output_formats)
response = await _worker_request(
self.pool,
worker,
"POST",
"/v1/tasks",
request=self.request,
- content=urlencode(form).encode(),
- headers={"content-type": "application/x-www-form-urlencoded"},
+ json_body={
+ "manifest": worker_manifest,
+ "tier": options.tier,
+ "ocr_mode": options.ocr_mode,
+ "output_formats": options.output_formats,
+ },
+ headers={"x-mineru-task-lease-seconds": "120"},
)
require_worker_generation(worker, reservation.generation)
payload = TaskStatusResponse.model_validate(_checked_json(response)).model_dump()
@@ -343,6 +381,7 @@ class RouterTaskBackend:
authorization = self.request.headers.get("authorization")
route.metadata.update(
task_protocol=True,
+ task_result_held=True,
active_counted=True,
reservation=reservation,
upstream_headers={"authorization": authorization} if authorization else {},
@@ -368,7 +407,11 @@ class RouterTaskBackend:
path,
request=self.request,
content=file_chunks(uploads[index].path),
- headers={**link["upload_headers"], "content-length": str(uploads[index].bytes)},
+ headers={
+ **link["upload_headers"],
+ "content-length": str(uploads[index].bytes),
+ "x-mineru-task-lease-seconds": "120",
+ },
)
if response.status_code >= 400:
_checked_json(response)
@@ -435,7 +478,7 @@ class RouterTaskBackend:
route.metadata.update(
payload={"job_id": task_id, "status": "failed", "files": []}, finalized_at=utc_now_iso()
)
- route.metadata.pop("upstream_headers", None)
+ route.metadata["task_result_retain_until"] = time.time()
else:
reservation.release()
for public_id in registered_inputs:
@@ -460,7 +503,7 @@ class RouterTaskBackend:
return route
async def get(self, task_id: str) -> TaskExecution:
- """只查询 worker 元数据并登记结果引用,ZIP 字节走已有 Files 流式代理。"""
+ """只查询 worker 元数据并登记结果引用,产物字节走已有 Files 流式代理。"""
route = self._route(task_id)
execution = await read_task_execution(route, self.pool, self.registry, request=self.request)
await self.finalize(route, execution.job, self.request)
@@ -468,7 +511,9 @@ class RouterTaskBackend:
async def cancel(self, task_id: str) -> None:
"""通过 worker tasks 取消准备或执行,成功后沿用一次性负载释放。"""
- route = self._route(task_id)
+ route = self.registry.find("job", task_id)
+ if route is None:
+ return
if route.metadata.get("upstream_lost"):
release_job_load(route, self.pool)
return
@@ -491,11 +536,41 @@ def install_task_error_handlers(app: FastAPI) -> None:
@app.exception_handler(RequestValidationError)
async def validation_error(_request: Request, exc: RequestValidationError) -> JSONResponse:
- """把路径及表单校验错误统一转换成 400。"""
+ """把路径及 JSON 校验错误统一转换成 400。"""
return JSONResponse(
{"error": {"type": "invalid_request_error", "code": "invalid_request", "message": str(exc)}},
status_code=400,
)
-__all__ = ["RouterTaskBackend", "install_task_error_handlers", "read_task_execution"]
+async def maintain_task_result_leases(registry: ResourceRegistry, pool: WorkerPool, *, release: bool = False) -> None:
+ """续租已结束父任务的子产物,进程关闭或公开保留期结束时释放上游租约。"""
+ for route in registry.list("job", include_expired=True):
+ if not route.metadata.get("task_result_held"):
+ continue
+ if not release and "task_result_retain_until" not in route.metadata:
+ continue
+ until = route.metadata.get("task_result_retain_until")
+ ended = release or (until is not None and until <= time.time())
+ worker = pool.get(route.worker_id)
+ headers = dict(route.metadata.get("upstream_headers") or {})
+ headers["x-mineru-task-lease-seconds"] = "0" if ended else "120"
+ try:
+ response = await _worker_request(pool, worker, "GET", f"/v1/tasks/{route.upstream_id}", headers=headers)
+ if response.status_code >= 400 and response.status_code != 404 and not ended:
+ continue
+ except ApiServerError:
+ if not ended:
+ continue
+ if ended:
+ route.metadata["task_result_held"] = False
+ route.metadata.pop("upstream_headers", None)
+ result_id = route.metadata.get("task_result_file_id")
+ result_route = next(
+ (item for item in registry.list("file", include_expired=True) if item.public_id == result_id), None
+ )
+ if result_route is not None:
+ result_route.metadata["task_result_held"] = False
+
+
+__all__ = ["RouterTaskBackend", "install_task_error_handlers", "read_task_execution", "maintain_task_result_leases"]
diff --git a/mineru/kit/router/workers.py b/mineru/kit/router/workers.py
index d26381f0..a6a45e37 100644
--- a/mineru/kit/router/workers.py
+++ b/mineru/kit/router/workers.py
@@ -519,12 +519,17 @@ class WorkerPool:
required_sources: set[str] | None = None,
preferred_worker_id: str | None = None,
required_outputs: set[str] | None = None,
+ required_task_outputs: set[str] | None = None,
require_flash: bool = False,
selection_kind: Literal["upload", "job"] = "job",
) -> WorkerState | None:
"""按能力和负载选取目标,文件归属仅在最低负载候选中优先。"""
eligible = self.capable_workers(
- tier=tier, required_sources=required_sources, required_outputs=required_outputs, require_flash=require_flash
+ tier=tier,
+ required_sources=required_sources,
+ required_outputs=required_outputs,
+ required_task_outputs=required_task_outputs,
+ require_flash=require_flash,
)
if not eligible:
return None
@@ -550,6 +555,7 @@ class WorkerPool:
tier: Tier | None,
required_sources: set[str] | None = None,
required_outputs: set[str] | None = None,
+ required_task_outputs: set[str] | None = None,
require_flash: bool = False,
) -> list[WorkerState]:
"""只读过滤完整能力组合,供预检复用;不改变轮询游标或预占负载。"""
@@ -559,6 +565,7 @@ class WorkerPool:
if (tier is None or tier in worker.tiers)
and (required_sources or set()).issubset(set(worker.features.get("sources") or []))
and (required_outputs or set()).issubset(set(worker.features.get("output_formats") or []))
+ and (required_task_outputs or set()).issubset(set(worker.features.get("task_output_formats") or []))
and (not require_flash or "flash" in worker.tiers)
]
@@ -569,6 +576,7 @@ class WorkerPool:
required_sources: set[str],
preferred_worker_id: str | None = None,
required_outputs: set[str] | None = None,
+ required_task_outputs: set[str] | None = None,
require_flash: bool = False,
) -> JobReservation | None:
"""在第一次网络等待前同步选择并预占解析 worker。"""
@@ -577,6 +585,7 @@ class WorkerPool:
required_sources=required_sources,
preferred_worker_id=preferred_worker_id,
required_outputs=required_outputs,
+ required_task_outputs=required_task_outputs,
require_flash=require_flash,
)
if worker is None:
diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.py
index b5779352..0f200036 100644
--- a/mineru/parser/api_server.py
+++ b/mineru/parser/api_server.py
@@ -80,6 +80,7 @@ from .tier import (
runtime_options_for_tier,
)
from .writer import DataWriter
+from .task_outputs import TASK_OUTPUT_FORMATS, TaskOutputFormat
_DEFAULT_API_SERVER_TIER: ServerTier = "standard"
_MAX_INLINE_BYTES_DEFAULT = 1024 * 1024
@@ -302,6 +303,7 @@ class HealthFeatures(BaseModel):
model_config = _PYDANTIC_CONFIG
webhook: bool = False
output_formats: list[OutputFormat] = Field(default_factory=lambda: list(_LOCAL_PARSE_OUTPUT_FORMATS))
+ task_output_formats: list[TaskOutputFormat] = Field(default_factory=lambda: list(TASK_OUTPUT_FORMATS))
sources: list[SourceType] = Field(default_factory=lambda: list(_BASE_PARSE_SOURCES))
@@ -1396,7 +1398,9 @@ class _JobRecord:
file_store: FileStore | None = None
usage_counted: bool = False
task_result_file_id: str | None = None
- task_error: ErrorDetail | None = None
+ task_output_formats: list[TaskOutputFormat] | None = None
+ retention_held: bool = False
+ retention_epoch: float | None = None
def __post_init__(self) -> None:
if self.files is None:
@@ -1473,7 +1477,8 @@ class JobStore:
self._tasks.pop(rec.id, None)
rec.finished_at = self._now()
if rec.file_store is not None:
- rec.file_store.finalize_outputs(rec.id, int(time.time()))
+ if not rec.retention_held:
+ rec.file_store.finalize_outputs(rec.id, int(rec.retention_epoch or time.time()))
rec.file_store.release_inputs(rec.input_blobs)
if not task.cancelled():
error = task.exception()
@@ -1577,14 +1582,24 @@ class JobStore:
return
now = time.time()
for job_id, rec in tuple(self._jobs.items()):
- if job_id in self._tasks or rec.finished_at is None:
+ if job_id in self._tasks or rec.finished_at is None or rec.retention_held:
continue
- finished = datetime.fromisoformat(rec.finished_at.replace("Z", "+00:00")).timestamp()
+ finished = rec.retention_epoch or datetime.fromisoformat(rec.finished_at.replace("Z", "+00:00")).timestamp()
if finished + self.retention_seconds <= now:
self._record_usage(rec)
self._jobs.pop(job_id)
self._completion_events.pop(job_id, None)
+ def release_task_result(self, job_id: str, finished: float) -> None:
+ """父 Task 收尾后才开始子作业与产物的保留期,不更改真实完成时间。"""
+ rec = self._jobs.get(job_id)
+ if rec is None:
+ return
+ rec.retention_held = False
+ rec.retention_epoch = finished
+ if rec.file_store is not None:
+ rec.file_store.finalize_outputs(job_id, int(finished))
+
def get(self, job_id: str) -> _JobRecord:
self.collect_expired()
rec = self._jobs.get(job_id)
@@ -1911,7 +1926,25 @@ async def _run_job(
if rec.status in {"canceled", "failed"}:
break
- # collect outputs
+ if rec.task_output_formats is not None:
+ from .task_outputs import build_task_output
+
+ try:
+ artifact = await run_sync(
+ build_task_output, result, rec.task_output_formats, pathlib.Path(tmpdir) / f"outputs_{i}"
+ )
+ if rec.status in {"canceled", "failed"}:
+ break
+ rec.task_result_file_id = await run_sync(
+ file_store.create_file_for_output_path,
+ pathlib.Path(fr.name).stem + artifact.suffix,
+ artifact,
+ job_id=rec.id,
+ )
+ except Exception as exc:
+ raise MineruError("result_packaging_failed", str(exc)) from exc
+
+ # Jobs 的原有产物策略与 Tasks 独立,不能向普通 Jobs 暴露 default 等产品选项。
out_formats = set(rec.output_formats)
output_files = OutputFiles()
@@ -2014,11 +2047,12 @@ _OPENAPI_TAGS: list[dict[str, str]] = [
_FASTAPI_DESCRIPTION = """\
Parse documents into structured Middle JSON via self-hosted or remote capacity.
-Submit a form manifest to `/v1/tasks`, upload only missing files to their returned
-URLs, then poll the task and download its `result_url`. Local servers also accept
-one multipart file. Manifest entries can instead provide a source `url`, with
-optional `bytes`; execution workers download these inputs in the background.
-Task status contains metadata only, never inline result bytes.
+Submit a JSON manifest to `/v1/tasks`, upload missing files to their one-hour URLs,
+then poll the task and download each completed file's `result_url`. Each file runs
+as soon as it is ready; other files may still be waiting for upload. Manifest
+entries can instead provide a source `url`, with optional `bytes`; workers download
+these inputs in the background. Choose one or more of default/docx/html/latex in
+`output_formats`. Task status contains metadata only, never inline result bytes.
The resource workflow remains: create an upload, complete it, submit a parse job for the
resulting file, then poll the job and fetch its outputs. Health and usage
endpoints report server readiness and quota state. Tiers (`flash`, `basic`,
@@ -2272,7 +2306,11 @@ class _OutputFileResponse(FileResponse):
super().__init__(
path,
filename=filename,
- media_type="application/zip" if filename.lower().endswith(".zip") else "application/octet-stream",
+ media_type={
+ ".zip": "application/zip",
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ ".html": "text/html",
+ }.get(pathlib.Path(filename).suffix.lower(), "application/octet-stream"),
)
except BaseException:
store.unpin_cached_blob(sha)
@@ -2335,6 +2373,7 @@ async def submit_parse_job(
job_id: str | None = None,
finalize: Callable[[_JobRecord], Awaitable[None]] | None = None,
input_specs: dict[int, _JobInputSpec] | None = None,
+ task_output_formats: list[TaskOutputFormat] | None = None,
) -> _JobRecord:
"""统一校验并提交后台解析任务,供 V1 Job 与便捷入口共同调用。"""
for index, entry in enumerate(body.files):
@@ -2418,6 +2457,8 @@ async def submit_parse_job(
if job_store._closing:
_raise_api_error(503, error_type="engine_error", code="server_shutting_down", message="Server is shutting down")
rec = job_store.create(body, file_store, job_id=job_id, input_specs=input_specs)
+ rec.task_output_formats = task_output_formats
+ rec.retention_held = task_output_formats is not None
url_timeout_val: int = request.app.state.url_timeout
allow_local_source_val: bool = request.app.state.allow_local_source
max_inline_bytes_val: int = request.app.state.max_inline_bytes
diff --git a/mineru/parser/task_api.py b/mineru/parser/task_api.py
index 1c76efa4..57e8e974 100644
--- a/mineru/parser/task_api.py
+++ b/mineru/parser/task_api.py
@@ -1,20 +1,16 @@
-"""本地服务与 Router 共用的表单任务、逐文件上传和结果链接协议。"""
+"""本地服务与 Router 共用的 JSON 任务、逐文件上传、执行和结果链接协议。"""
from __future__ import annotations
import asyncio
-import copy
import hashlib
-import json
import logging
import secrets
import shutil
import tempfile
import time
-import zipfile
from collections.abc import AsyncIterator, Callable
from dataclasses import dataclass, field, replace
-from datetime import datetime
from pathlib import Path
from typing import Any, Literal, NoReturn, Protocol
from urllib.parse import quote
@@ -22,8 +18,6 @@ from urllib.parse import quote
from fastapi import APIRouter, Request, Response
from fastapi.responses import JSONResponse
from pydantic import AnyHttpUrl, BaseModel, ConfigDict, Field, ValidationError, model_validator
-from starlette.datastructures import UploadFile
-from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.requests import ClientDisconnect
from ..errors import MineruError
@@ -41,22 +35,22 @@ from .api_server import (
JobFileEntry,
JobProgress,
JobStore,
- OutputFiles,
UrlSource,
_JobInputMetadata,
_JobInputSpec,
- _JobRecord,
_raise_api_error,
_require_model_preload_ready,
_validate_source_policy,
submit_parse_job,
)
from .page_range import normalize_page_range_input
+from .task_outputs import TaskOutputFormat
MAX_TASK_FILES = 100
TASK_UPLOAD_TTL = 3600
TERMINAL_TASK_STATUSES = frozenset({"completed", "partial", "failed", "canceled"})
TaskStatus = Literal["waiting_upload", "queued", "running", "completed", "partial", "failed", "canceled"]
+TaskFileState = Literal["waiting_upload", "queued", "running", "completed", "failed", "canceled"]
logger = logging.getLogger(__name__)
@@ -83,15 +77,19 @@ class TaskManifestItem(BaseModel):
class UploadTaskOptions(BaseModel):
- """解析选项仅来自表单,文件元数据独立保存在 manifest 中。"""
+ """解析选项仅来自 JSON 主体,文件元数据独立保存在 manifest 中。"""
model_config = ConfigDict(extra="forbid")
tier: Tier | None = None
ocr_mode: Literal["auto", "txt", "ocr"] = "auto"
page_range: str = ""
- output_formats: list[Literal["markdown", "middle_json", "structured_content", "zip"]] = Field(
- default_factory=lambda: ["markdown"], min_length=1
- )
+ output_formats: list[TaskOutputFormat] = Field(default_factory=lambda: ["default"], min_length=1)
+
+
+class CreateTaskRequest(UploadTaskOptions):
+ """严格 JSON 创建请求,清单是数组而不是编码后的字符串。"""
+
+ manifest: list[TaskManifestItem] = Field(min_length=1, max_length=MAX_TASK_FILES)
class TaskUploadLink(BaseModel):
@@ -107,27 +105,26 @@ class TaskUploadLink(BaseModel):
class TaskFileStatus(TaskManifestItem):
"""同时提供上传准备情况与逐文件解析状态,禁止内联解析正文。"""
- upload_status: Literal["pending", "ready", "not_required"]
+ upload_status: Literal["pending", "ready", "not_required", "expired"]
file_id: str | None = None
name: str
- status: Literal["waiting_upload", "queued", "running", "completed", "failed", "canceled"]
+ status: TaskFileState
parse: FileParseInfo | None = None
- output_files: OutputFiles | None = None
+ result_url: str | None = None
error: ErrorDetail | None = None
class TaskStatusResponse(BaseModel):
- """任务状态只携带元数据;最终 ZIP 由独立下载链接提供。"""
+ """任务状态只携带元数据;每个成功文件提供自己的下载链接。"""
task_id: str
status: TaskStatus
status_url: str
- result_url: str | None = None
created_at: str
started_at: str | None = None
finished_at: str | None = None
tier: Tier | None = None
- output_formats: list[str]
+ output_formats: list[TaskOutputFormat]
progress: JobProgress
files: list[TaskFileStatus]
uploads: list[TaskUploadLink] = Field(default_factory=list)
@@ -148,7 +145,7 @@ class TaskUpload:
@dataclass(frozen=True)
class TaskExecution:
- """在后台适配器之间传递执行快照、实际输入元数据及本部署的 ZIP File 标识。"""
+ """在适配器之间传递单文件执行快照、实际输入元数据及本部署的产物标识。"""
job: dict[str, Any]
result_file_id: str | None = None
@@ -161,6 +158,14 @@ class TaskBackend(Protocol):
owner_scope: str
+ def fork(self) -> TaskBackend:
+ """为每个文件创建独立的引用和执行上下文。"""
+ ...
+
+ async def release_result(self, task_id: str, finished: float) -> None:
+ """父任务收尾后解除子结果租约,并开始正常保留期。"""
+ ...
+
async def validate(self, options: UploadTaskOptions, manifest: list[TaskManifestItem]) -> None:
"""在接单之前校验部署能力,不能预占解析名额。"""
...
@@ -184,7 +189,7 @@ class TaskBackend(Protocol):
...
async def get(self, task_id: str) -> TaskExecution:
- """只查询执行和产物元数据,不读取 ZIP 内容。"""
+ """只查询执行和产物元数据,不读取结果文件内容。"""
...
async def cancel(self, task_id: str) -> None:
@@ -227,12 +232,6 @@ async def file_chunks(path: Path) -> AsyncIterator[bytes]:
yield chunk
-async def _upload_chunks(upload: UploadFile) -> AsyncIterator[bytes]:
- """分块读取已经由表单解析器暂存的单个直传文件。"""
- while chunk := await upload.read(1024 * 1024):
- yield chunk
-
-
async def _save_upload(
chunks: AsyncIterator[bytes],
path: Path,
@@ -268,77 +267,67 @@ async def _save_upload(
raise
-async def _read_submission(
- request: Request, directory: Path
-) -> tuple[UploadTaskOptions, list[TaskManifestItem], TaskUpload | None]:
- """解析含上传或 URL 来源的表单清单;拒绝旧 JSON、原始字节及查询参数。"""
+async def _read_submission(request: Request) -> tuple[UploadTaskOptions, list[TaskManifestItem]]:
+ """只读取 JSON 清单,严格拒绝表单、直传字节和 URL 查询参数。"""
if request.query_params:
- _invalid("POST parameters must be supplied in the form body, not the URL")
+ _invalid("POST parameters must be supplied in the JSON body, not the URL")
media_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
- if media_type not in {"application/x-www-form-urlencoded", "multipart/form-data"}:
- _invalid("Use application/x-www-form-urlencoded or multipart/form-data", status_code=415)
+ if media_type != "application/json":
+ _invalid("Use application/json", status_code=415)
try:
- async with request.form(max_files=1, max_fields=32) as form:
- for key in form:
- if key not in {"output_formats", "files"} and len(form.getlist(key)) != 1:
- _invalid(f"Duplicate form field: {key}", param=key)
- params = {key: form[key] for key in form if key not in {"manifest", "files", "output_formats"}}
- if "output_formats" in form:
- params["output_formats"] = form.getlist("output_formats")
- options = UploadTaskOptions.model_validate(params)
- options.page_range = normalize_page_range_input(options.page_range)
- options.output_formats = list(dict.fromkeys([*options.output_formats, "zip"]))
- manifest: list[TaskManifestItem] = []
- if "manifest" in form:
- raw = form["manifest"]
- if not isinstance(raw, str):
- _invalid("manifest must be a JSON text field", param="manifest")
- values = json.loads(raw)
- if not isinstance(values, list) or not 1 <= len(values) <= MAX_TASK_FILES:
- _invalid("manifest must contain between 1 and 100 files", param="manifest")
- manifest = [TaskManifestItem.model_validate(item) for item in values]
- if len({item.client_file_id for item in manifest}) != len(manifest):
- _invalid("client_file_id must be unique within a task", param="manifest")
- files = form.getlist("files")
- direct: TaskUpload | None = None
- if files:
- if len(files) != 1 or (manifest and len(manifest) != 1):
- _invalid("Multipart direct upload supports one file; submit a manifest for multiple files", param="files")
- if manifest and manifest[0].url is not None:
- _invalid("url and multipart file bytes cannot be supplied together", param="files")
- file = files[0]
- if not isinstance(file, UploadFile) or not file.filename:
- _invalid("files must contain one named file", param="files")
- filename = manifest[0].filename if manifest else file.filename
- direct = await _save_upload(
- _upload_chunks(file),
- directory / "direct",
- filename,
- file.content_type or "application/octet-stream",
- expected=manifest[0] if manifest else None,
- )
- if not manifest:
- manifest = [TaskManifestItem(client_file_id="f1", filename=filename, bytes=direct.bytes)]
- if not manifest:
- _invalid("Supply manifest or one files field", param="manifest")
- for item in manifest:
- item.page_range = normalize_page_range_input(
- item.page_range if item.page_range is not None else options.page_range
- )
- return options, manifest, direct
- except StarletteHTTPException as exc:
- _invalid(str(exc.detail), status_code=exc.status_code)
+ body = CreateTaskRequest.model_validate(await request.json())
+ if len({item.client_file_id for item in body.manifest}) != len(body.manifest):
+ _invalid("client_file_id must be unique within a task", param="manifest")
+ options = UploadTaskOptions.model_validate(body.model_dump(exclude={"manifest"}))
+ options.page_range = normalize_page_range_input(options.page_range)
+ options.output_formats = list(dict.fromkeys(options.output_formats))
+ for item in body.manifest:
+ item.page_range = normalize_page_range_input(item.page_range if item.page_range is not None else options.page_range)
+ return options, body.manifest
except ClientDisconnect:
- _invalid("Upload interrupted; retry the request", code="upload_interrupted")
+ _invalid("Request interrupted", code="request_interrupted")
except MineruError as exc:
_invalid(str(exc), code=exc.code, param=exc.param)
except (ValidationError, ValueError) as exc:
_invalid(str(exc))
+def _retention_lease(request: Request) -> int | None:
+ """读取 Router 的有界结果租约,避免父任务结束前 worker 提前清理子文件。"""
+ value = request.headers.get("x-mineru-task-lease-seconds")
+ if value is None:
+ return None
+ try:
+ seconds = int(value)
+ if not 0 <= seconds <= TASK_UPLOAD_TTL:
+ raise ValueError
+ except ValueError:
+ _invalid("Task result lease must be between 0 and 3600 seconds")
+ return seconds
+
+
+@dataclass
+class _TaskFileRecord:
+ """每个文件独立拥有准备引用、执行 ID 和一次性提交句柄。"""
+
+ backend: TaskBackend
+ execution_id: str = field(default_factory=JobStore._new_job_id)
+ status: TaskFileState = "waiting_upload"
+ upload: TaskUpload | None = None
+ upload_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
+ upload_active: bool = False
+ expired: bool = False
+ execution: TaskExecution | None = None
+ operation: asyncio.Task[None] | None = None
+ submitted: bool = False
+ finished: asyncio.Event = field(default_factory=asyncio.Event)
+ lease_refresh_at: float = 0
+ error: ErrorDetail | None = None
+
+
@dataclass
class _TaskRecord:
- """只保存上传准备与执行映射;解析并发仍由既有 JobStore 管理。"""
+ """父 Task 只聚合文件状态,独立子 Job 继续使用现有解析并发。"""
id: str
backend: TaskBackend
@@ -346,25 +335,24 @@ class _TaskRecord:
manifest: list[TaskManifestItem]
directory: Path
expires_at: int
+ files: list[_TaskFileRecord]
created_at: str = field(default_factory=JobStore._now)
status: TaskStatus = "waiting_upload"
- uploads: dict[int, TaskUpload] = field(default_factory=dict)
- upload_locks: dict[int, asyncio.Lock] = field(default_factory=dict)
refresh_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
- execution: TaskExecution | None = None
+ changed: asyncio.Event = field(default_factory=asyncio.Event)
operation: asyncio.Task[None] | None = None
- submitted: bool = False
- active_uploads: int = 0
finished_at: str | None = None
finished_epoch: float | None = None
+ retention_epoch: float | None = None
+ lease_expires_at: float = 0
error: ErrorDetail | None = None
class TaskStore:
- """管理跨请求上传租约、稳定 ID 和提交一次语义,不建立第二个解析队列。"""
+ """管理固定上传窗口和逐文件执行,不建立第二个解析队列。"""
def __init__(self, retention_seconds: int) -> None:
- """在应用创建时准备私有暂存目录,不在模块导入阶段产生副作用。"""
+ """只在创建应用时分配暂存目录,模块导入不产生副作用。"""
self.retention_seconds = retention_seconds
self._temporary = tempfile.TemporaryDirectory(prefix="mineru-tasks-")
self._root = Path(self._temporary.name)
@@ -374,188 +362,282 @@ class TaskStore:
self._closing = False
def start(self) -> None:
- """启动独立的准备记录回收,关闭产物保留策略时也能清理过期上传。"""
+ """启动过期扫描,关闭正常保留期也仍然执行上传截止时间。"""
if self._collector is None and not self._closing:
self._collector = asyncio.create_task(self._collect_loop(), name="mineru-task-retention")
async def _collect_loop(self) -> None:
- """定期回收等待上传的孤立任务和超过保留期的终态快照。"""
+ """定期清理过期元数据;上传与状态请求也执行同一截止检查。"""
while True:
await asyncio.sleep(60)
self.collect_expired()
- def _release(self, record: _TaskRecord, *, rollback: bool) -> None:
- """没有在途写入时释放准备引用,避免取消与落盘并发导致路径提前消失。"""
- if record.active_uploads:
+ def _aggregate(self, record: _TaskRecord) -> None:
+ """按运行、排队、等待的优先级聚合,所有文件终结后再发布成功或部分成功。"""
+ if record.status == "canceled":
return
- record.backend.release_uploads(rollback=rollback)
- shutil.rmtree(record.directory, ignore_errors=True)
-
- def _finish(self, record: _TaskRecord, status: TaskStatus, error: ErrorDetail | None = None) -> None:
- """统一记录终态时间,错误、过期和取消采用同一保留边界。"""
- record.status = status
- record.error = error
- record.finished_at = JobStore._now()
- record.finished_epoch = time.time()
+ previous = record.status
+ states = [file.status for file in record.files]
+ if "running" in states:
+ record.status = "running"
+ elif "queued" in states:
+ record.status = "queued"
+ elif "waiting_upload" in states:
+ record.status = "waiting_upload"
+ else:
+ completed = states.count("completed")
+ record.status = "completed" if completed == len(states) else ("partial" if completed else "failed")
+ if record.status in TERMINAL_TASK_STATUSES and record.finished_epoch is None:
+ record.finished_at = JobStore._now()
+ record.finished_epoch = time.time()
+ if record.status != previous:
+ record.changed.set()
+
+ def _expire_uploads(self, record: _TaskRecord) -> None:
+ """只终结尚未受理上传的文件;截止前已经受理的流允许继续完成。"""
+ if record.expires_at > time.time() or record.status == "canceled":
+ return
+ for file in record.files:
+ if file.status == "waiting_upload" and not file.upload_active:
+ file.expired = True
+ file.status = "failed"
+ file.error = ErrorDetail(type="invalid_request_error", code="upload_expired", message="Upload expired")
+ self._aggregate(record)
def collect_expired(self) -> None:
- """等待上传到期时释放缓存租约;活动写入与后台执行不被中途回收。"""
+ """上传到期按文件处理,记录仅在清理结束并超过父任务保留期后移除。"""
now = time.time()
for task_id, record in tuple(self._records.items()):
- if record.status == "waiting_upload" and record.expires_at <= now and not record.active_uploads:
- self._finish(
- record, "failed", ErrorDetail(type="invalid_request_error", code="upload_expired", message="Upload expired")
- )
- self._release(record, rollback=True)
+ self._expire_uploads(record)
if (
self.retention_seconds
- and record.finished_epoch is not None
- and record.finished_epoch + self.retention_seconds <= now
- and not record.active_uploads
- and (record.operation is None or record.operation.done())
+ and record.retention_epoch is not None
+ and record.retention_epoch + self.retention_seconds <= now
+ and record.operation is not None
+ and record.operation.done()
):
- self._release(record, rollback=not record.submitted)
self._records.pop(task_id, None)
+ shutil.rmtree(record.directory, ignore_errors=True)
def lookup(self, task_id: str, owner_scope: str) -> _TaskRecord:
- """只有当前调用方可以读写任务,未知 ID 与越权 ID 使用同一错误。"""
+ """未知与越权任务使用相同错误,避免跨调用方探测。"""
self.collect_expired()
record = self._records.get(task_id)
if record is None or record.backend.owner_scope != owner_scope:
_invalid(f"Task {task_id} not found", status_code=404, code="task_not_found")
return record
+ def update_lease(self, record: _TaskRecord, seconds: int | None) -> None:
+ """续租只保护结果保留期,从不延长上传窗口,也不复活已释放的结果。"""
+ if seconds is None:
+ return
+ if seconds and record.retention_epoch is not None:
+ _invalid("Task result lease has already ended", status_code=409, code="task_lease_ended")
+ record.lease_expires_at = time.time() + seconds if seconds else 0
+ record.changed.set()
+
async def create(
- self, backend: TaskBackend, options: UploadTaskOptions, manifest: list[TaskManifestItem], direct: TaskUpload | None
+ self, backend: TaskBackend, options: UploadTaskOptions, manifest: list[TaskManifestItem], *, lease_seconds: int = 0
) -> _TaskRecord:
- """校验并固定已命中源文件;客户端上传项齐备后提交后台执行。"""
+ """先完整校验清单并固定缓存,再为各个就绪文件独立提交执行。"""
if self._closing:
_invalid("Server is shutting down", status_code=503, code="server_shutting_down")
await backend.validate(options, manifest)
task_id = JobStore._new_job_id()
- record = _TaskRecord(task_id, backend, options, manifest, self._root / task_id, int(time.time()) + TASK_UPLOAD_TTL)
+ record = _TaskRecord(
+ task_id,
+ backend,
+ options,
+ manifest,
+ self._root / task_id,
+ int(time.time()) + TASK_UPLOAD_TTL,
+ [_TaskFileRecord(backend.fork()) for _ in manifest],
+ )
+ self.update_lease(record, lease_seconds)
try:
for index, item in enumerate(manifest):
- if item.url is not None:
- continue
- upload = (
- direct
- if direct is not None
- else (await backend.find_upload(item.sha256sum, item.filename) if item.sha256sum else None)
- )
- if upload is not None:
- if upload.bytes != item.bytes:
- _invalid("Declared size does not match cached bytes", code="upload_size_mismatch")
- record.uploads[index] = await backend.retain_upload(upload)
+ file = record.files[index]
+ if item.url is None and item.sha256sum:
+ upload = await file.backend.find_upload(item.sha256sum, item.filename)
+ if upload is not None:
+ if upload.bytes != item.bytes:
+ _invalid("Declared size does not match cached bytes", code="upload_size_mismatch")
+ file.upload = await file.backend.retain_upload(upload)
self._records[task_id] = record
self.start()
- self._maybe_start(record)
+ for index, item in enumerate(manifest):
+ if item.url is not None or record.files[index].upload is not None:
+ self._start_file(record, index)
+ record.operation = asyncio.create_task(self._monitor(record), name=f"mineru-task-{task_id}")
return record
except BaseException:
- backend.release_uploads(rollback=True)
+ for file in record.files:
+ file.backend.release_uploads(rollback=True)
raise
- def _maybe_start(self, record: _TaskRecord) -> None:
- """事件循环内原子切换准备状态,最后多个上传并发完成也只创建一个执行句柄。"""
- if record.status == "waiting_upload" and all(
- item.url is not None or index in record.uploads for index, item in enumerate(record.manifest)
- ):
- record.status = "queued"
- record.operation = asyncio.create_task(self._dispatch(record), name=f"mineru-task-{record.id}")
-
- def operation_finished(operation: asyncio.Task[None]) -> None:
- """覆盖首次调度前取消,且让取消后的保留期从准备引用清理完成时开始。"""
- if record.status == "canceled":
- self._finish(record, "canceled")
- self._release(record, rollback=not record.submitted)
- if not operation.cancelled() and operation.exception() is not None:
- error = operation.exception()
- logger.error("Task cleanup failed: %s", record.id, exc_info=(type(error), error, error.__traceback__))
-
- record.operation.add_done_callback(operation_finished)
-
- def _apply_execution(self, record: _TaskRecord, execution: TaskExecution) -> None:
- """更新已发布的执行快照,不能用迟到响应覆盖取消或失败终态。"""
- if record.status in TERMINAL_TASK_STATUSES:
+ def _start_file(self, record: _TaskRecord, index: int) -> None:
+ """事件循环内同步登记提交句柄,重复 PUT 不能创建第二个子作业。"""
+ file = record.files[index]
+ if file.operation is not None or file.status != "waiting_upload" or record.status == "canceled":
+ return
+ file.status = "queued"
+ record.changed.set()
+ file.operation = asyncio.create_task(self._dispatch_file(record, index), name=f"mineru-task-file-{file.execution_id}")
+ self._aggregate(record)
+
+ def _apply_execution(self, record: _TaskRecord, file: _TaskFileRecord, execution: TaskExecution) -> None:
+ """只接受单文件执行快照,取消和已发布终态不被迟到响应覆盖。"""
+ if file.status in TERMINAL_TASK_STATUSES:
return
status = execution.job.get("status")
- if status not in {"queued", "running", *TERMINAL_TASK_STATUSES}:
- _invalid("Invalid task status from execution backend", code="invalid_response", status_code=502)
- if status in {"completed", "partial"} and execution.result_file_id is None:
- _invalid("Completed task has no ZIP file", code="invalid_response", status_code=502)
- record.execution = execution
- record.status = status
+ if status not in {"queued", "running", "completed", "failed", "canceled"}:
+ _invalid("Invalid file status from execution backend", code="invalid_response", status_code=502)
+ if status == "completed" and execution.result_file_id is None:
+ _invalid("Completed file has no result", code="invalid_response", status_code=502)
+ if len(execution.job.get("files") or []) != 1:
+ _invalid("Expected one file from execution backend", code="invalid_response", status_code=502)
+ if status != file.status:
+ record.changed.set()
+ file.execution = execution
+ file.status = status
+ file.error = execution.error
if status in TERMINAL_TASK_STATUSES:
- self._finish(record, status, execution.error)
- record.finished_at = execution.job.get("finished_at") or record.finished_at
- if record.finished_at is not None:
- record.finished_epoch = datetime.fromisoformat(record.finished_at.replace("Z", "+00:00")).timestamp()
+ file.finished.set()
+ file.lease_refresh_at = time.monotonic() + 30
+ self._aggregate(record)
async def refresh(self, record: _TaskRecord) -> None:
- """状态刷新只查询元数据;串行化并发查询,防止旧快照覆盖新状态。"""
+ """并发刷新独立文件;成功文件仍续租 worker 结果直到父任务收尾。"""
async with record.refresh_lock:
- if record.submitted and record.status not in TERMINAL_TASK_STATUSES:
- self._apply_execution(record, await record.backend.get(record.id))
-
- async def _dispatch(self, record: _TaskRecord) -> None:
- """提交与监控由应用持有,HTTP 断连不取消已经接受的任务。"""
- try:
- execution = await record.backend.submit(record.id, record.options, record.manifest, record.uploads)
- record.submitted = True
- self._apply_execution(record, execution)
- self._release(record, rollback=False)
- while record.status not in TERMINAL_TASK_STATUSES:
- await asyncio.sleep(1)
+ self._expire_uploads(record)
+ if record.status in TERMINAL_TASK_STATUSES:
+ return
+ targets = [
+ file
+ for file in record.files
+ if file.submitted
+ and file.status not in {"failed", "canceled"}
+ and (file.status != "completed" or file.lease_refresh_at <= time.monotonic())
+ ]
+ results = await asyncio.gather(*(file.backend.get(file.execution_id) for file in targets), return_exceptions=True)
+ for file, result in zip(targets, results):
+ if isinstance(result, BaseException):
+ if (
+ isinstance(result, ApiServerError)
+ and result.status_code in {408, 429, 500, 502, 503, 504}
+ and result.error.code not in {"invalid_response", "invalid_upstream_response"}
+ ):
+ logger.warning("Task file refresh failed: %s: %s", file.execution_id, result.error.code)
+ continue
+ if file.status not in TERMINAL_TASK_STATUSES:
+ file.status = "failed"
+ file.error = (
+ result.error
+ if isinstance(result, ApiServerError)
+ else ErrorDetail(type="api_error", code="task_refresh_failed", message=str(result))
+ )
+ if file.operation is not None:
+ file.operation.cancel()
+ continue
try:
- await self.refresh(record)
+ self._apply_execution(record, file, result)
+ if file.status == "completed":
+ file.lease_refresh_at = time.monotonic() + 30
except ApiServerError as exc:
- if exc.status_code not in {408, 429, 500, 502, 503, 504} or exc.error.code in {
- "invalid_response",
- "invalid_upstream_response",
- }:
- raise
- logger.warning("Task status refresh failed: %s: %s", record.id, exc.error.code)
+ file.status = "failed"
+ file.error = exc.error
+ if file.operation is not None:
+ file.operation.cancel()
+ self._aggregate(record)
+
+ async def _dispatch_file(self, record: _TaskRecord, index: int) -> None:
+ """每个文件独立提交,失败或取消只清理自己的作业与源文件租约。"""
+ file = record.files[index]
+ try:
+ execution = await file.backend.submit(
+ file.execution_id, record.options, [record.manifest[index]], {0: file.upload} if file.upload is not None else {}
+ )
+ file.submitted = True
+ self._apply_execution(record, file, execution)
+ file.backend.release_uploads(rollback=False)
+ if file.status not in TERMINAL_TASK_STATUSES:
+ await file.finished.wait()
except asyncio.CancelledError:
- if record.submitted and record.status not in {"completed", "partial", "failed"}:
- try:
- await drain_future(asyncio.create_task(record.backend.cancel(record.id)))
- except Exception:
- logger.exception("Task cancellation cleanup failed: %s", record.id)
- if record.status not in TERMINAL_TASK_STATUSES:
- self._finish(record, "canceled")
+ try:
+ await drain_future(asyncio.create_task(file.backend.cancel(file.execution_id)))
+ except Exception:
+ logger.exception("Task file cancellation failed: %s", file.execution_id)
+ if file.status not in TERMINAL_TASK_STATUSES:
+ file.status = "canceled"
except Exception as exc:
- error = (
- exc.error
- if isinstance(exc, ApiServerError)
- else ErrorDetail(type="api_error", code="task_submission_failed", message=str(exc))
- )
- if record.status not in TERMINAL_TASK_STATUSES:
- self._finish(record, "failed", error)
- if record.submitted:
- try:
- await drain_future(asyncio.create_task(record.backend.cancel(record.id)))
- except Exception:
- logger.exception("Failed task cleanup could not reach execution backend: %s", record.id)
- logger.exception("Task execution failed: %s", record.id)
+ if file.status not in TERMINAL_TASK_STATUSES:
+ file.status = "failed"
+ file.error = (
+ exc.error
+ if isinstance(exc, ApiServerError)
+ else ErrorDetail(type="api_error", code="task_submission_failed", message=str(exc))
+ )
+ try:
+ await file.backend.cancel(file.execution_id)
+ except Exception:
+ logger.exception("Task file failure cleanup failed: %s", file.execution_id)
+ finally:
+ file.finished.set()
+ record.changed.set()
+ file.backend.release_uploads(rollback=not file.submitted)
+ self._aggregate(record)
+
+ async def _monitor(self, record: _TaskRecord) -> None:
+ """应用持有父任务监控;HTTP 断连不影响执行,所有子文件清理后才开始保留期。"""
+ try:
+ while record.status not in TERMINAL_TASK_STATUSES:
+ record.changed.clear()
+ await self.refresh(record)
+ if record.status not in TERMINAL_TASK_STATUSES:
+ await self._wait_for_change(record)
+ operations = [file.operation for file in record.files if file.operation is not None]
+ if operations:
+ await asyncio.gather(*operations, return_exceptions=True)
+ while any(file.upload_active for file in record.files) or record.lease_expires_at > time.time():
+ record.changed.clear()
+ await self._wait_for_change(record)
+ finished = time.time()
+ for file in record.files:
+ await file.backend.release_result(file.execution_id, finished)
+ file.backend.release_uploads(rollback=not file.submitted)
+ record.retention_epoch = finished
+ except Exception:
+ logger.exception("Task result cleanup failed: %s", record.id)
finally:
- self._release(record, rollback=not record.submitted)
+ if not any(file.upload_active for file in record.files):
+ shutil.rmtree(record.directory, ignore_errors=True)
+
+ async def _wait_for_change(self, record: _TaskRecord) -> None:
+ """状态变更即时唤醒;没有事件时每秒检查执行与到期边界。"""
+ try:
+ await asyncio.wait_for(record.changed.wait(), timeout=1)
+ except asyncio.TimeoutError:
+ pass
async def upload(self, record: _TaskRecord, client_file_id: str, request: Request) -> bool:
- """独立接收一个文件;返回是否跳过主体,供 HTTP/1.1 正确关闭连接。"""
- index = next((index for index, item in enumerate(record.manifest) if item.client_file_id == client_file_id), None)
+ """在接收主体前检查固定期限,已受理流不因父任务状态变化中止。"""
+ index = next((i for i, item in enumerate(record.manifest) if item.client_file_id == client_file_id), None)
if index is None:
_invalid("Unknown client_file_id", status_code=404, code="upload_not_found")
- if record.manifest[index].url is not None:
- _invalid("URL inputs do not accept uploads", status_code=400, code="invalid_request")
- lock = record.upload_locks.setdefault(index, asyncio.Lock())
- async with lock:
- if record.status in {"failed", "canceled"}:
- _invalid("Task no longer accepts uploads", status_code=409, code="task_already_terminal")
- if index in record.uploads:
+ expected = record.manifest[index]
+ if expected.url is not None:
+ _invalid("URL inputs do not accept uploads")
+ file = record.files[index]
+ async with file.upload_lock:
+ if record.expires_at <= time.time():
+ self._expire_uploads(record)
+ _invalid("Upload link expired", status_code=410, code="upload_expired")
+ if record.status == "canceled":
+ _invalid("Task was canceled", status_code=409, code="task_already_terminal")
+ if file.upload is not None:
return True
- if record.status != "waiting_upload" or record.expires_at <= time.time():
- _invalid("Task no longer accepts uploads", status_code=409, code="task_already_terminal")
- expected = record.manifest[index]
+ if file.status != "waiting_upload":
+ _invalid("File no longer accepts uploads", status_code=409, code="file_already_terminal")
length = request.headers.get("content-length")
if length is not None:
try:
@@ -564,13 +646,13 @@ class TaskStore:
_invalid("Invalid Content-Length", code="upload_size_mismatch")
if declared != expected.bytes:
_invalid("Content-Length does not match manifest bytes", code="upload_size_mismatch")
- record.active_uploads += 1
+ file.upload_active = True
record.directory.mkdir(parents=True, exist_ok=True)
path = record.directory / secrets.token_hex(16)
def was_canceled() -> bool:
- """每次接收数据时检查取消状态,避免继续写入已取消任务的剩余主体。"""
- return record.status != "waiting_upload"
+ """只在本文件被取消时中止已受理上传,不把上传截止时间当作传输超时。"""
+ return record.status == "canceled" or file.status == "canceled"
try:
upload = await _save_upload(
@@ -581,50 +663,54 @@ class TaskStore:
expected=expected,
canceled=was_canceled,
)
- if record.status != "waiting_upload":
+ if was_canceled():
_invalid("Task was canceled during upload", status_code=409, code="task_already_terminal")
- retained = await record.backend.retain_upload(upload)
- if record.status != "waiting_upload":
+ retained = await file.backend.retain_upload(upload)
+ if was_canceled():
+ file.backend.release_uploads(rollback=True)
_invalid("Task was canceled during upload", status_code=409, code="task_already_terminal")
- record.uploads[index] = retained
- self._maybe_start(record)
+ file.upload = retained
+ self._start_file(record, index)
return False
except ClientDisconnect:
_invalid("Upload interrupted; retry this file on the same task", code="upload_interrupted")
finally:
path.unlink(missing_ok=True)
- record.active_uploads -= 1
- if record.status in TERMINAL_TASK_STATUSES:
- self._release(record, rollback=not record.submitted)
- if record.status == "canceled" and not record.active_uploads:
- self._finish(record, "canceled")
+ file.upload_active = False
+ record.changed.set()
+ self._expire_uploads(record)
async def cancel(self, record: _TaskRecord, *, wait: bool = True) -> None:
- """取消准备或执行阶段,后台清理结束之前不删除仍在使用的源文件。"""
+ """保留已完成结果,只取消未完成文件并等待真实子作业清理。"""
if record.status in TERMINAL_TASK_STATUSES:
_invalid(f"Task is {record.status}", status_code=409, code="task_already_terminal")
- self._finish(record, "canceled")
- if record.operation is not None and not record.operation.done():
- record.operation.cancel()
- if not wait:
- return
- await drain_future(asyncio.gather(record.operation, return_exceptions=True))
- self._finish(record, "canceled")
- self._release(record, rollback=not record.submitted)
+ record.status = "canceled"
+ record.finished_at = JobStore._now()
+ record.finished_epoch = time.time()
+ record.changed.set()
+ for file in record.files:
+ if file.status not in TERMINAL_TASK_STATUSES:
+ file.status = "canceled"
+ if file.operation is not None:
+ file.operation.cancel()
+ if wait and record.operation is not None:
+ record.lease_expires_at = 0
+ record.changed.set()
+ await drain_future(record.operation)
async def shutdown(self) -> None:
- """关闭时先停止提交和监控,再释放所有准备阶段引用与暂存目录。"""
+ """停止接单并排空全部文件执行和结果租约,最后释放临时目录。"""
self._closing = True
if self._collector is not None:
self._collector.cancel()
await asyncio.gather(self._collector, return_exceptions=True)
for record in tuple(self._records.values()):
+ record.lease_expires_at = 0
if record.status not in TERMINAL_TASK_STATUSES:
- await self.cancel(record)
- elif record.operation is not None and not record.operation.done():
- record.operation.cancel()
- await drain_future(asyncio.gather(record.operation, return_exceptions=True))
- self._release(record, rollback=not record.submitted)
+ await self.cancel(record, wait=False)
+ await asyncio.gather(
+ *(record.operation for record in self._records.values() if record.operation is not None), return_exceptions=True
+ )
self._temporary.cleanup()
@@ -634,28 +720,42 @@ def _url(request: Request, path: str) -> str:
def task_payload(record: _TaskRecord, request: Request) -> dict[str, Any]:
- """将任务准备记录与执行元数据合并,不读取任何解析产物字节。"""
- job = record.execution.job if record.execution is not None else {}
- results = job.get("files") or []
+ """逐文件合并上传与执行元数据,成功文件立即给出独立下载链接。"""
files: list[dict[str, Any]] = []
links: list[dict[str, Any]] = []
- for index, item in enumerate(record.manifest):
- upload = record.uploads.get(index)
+ starts: list[str] = []
+ for item, state in zip(record.manifest, record.files):
file = item.model_dump()
+ upload = state.upload
file.update(
name=item.filename,
- upload_status="not_required" if item.url is not None else ("ready" if upload is not None else "pending"),
- status="queued" if upload is not None or item.url is not None else "waiting_upload",
+ upload_status="not_required"
+ if item.url is not None
+ else ("ready" if upload is not None else ("expired" if state.expired else "pending")),
+ status=state.status,
file_id=upload.file_id if upload else None,
+ result_url=None,
)
- if index < len(results):
- file.update(results[index])
- if record.execution is not None and (metadata := record.execution.input_metadata.get(index)) is not None:
- file.update(bytes=metadata.bytes, sha256sum=metadata.sha256sum)
- if record.status == "canceled" and file["status"] not in {"completed", "failed"}:
- file["status"] = "canceled"
+ if state.execution is not None:
+ job = state.execution.job
+ results = job.get("files") or []
+ if results:
+ file.update({key: results[0].get(key) for key in ("name", "file_id", "page_range", "parse", "error")})
+ if job.get("started_at"):
+ starts.append(job["started_at"])
+ if (metadata := state.execution.input_metadata.get(0)) is not None:
+ file.update(bytes=metadata.bytes, sha256sum=metadata.sha256sum)
+ if state.status == "completed" and state.execution.result_file_id:
+ file["result_url"] = _url(request, f"/v1/files/{quote(state.execution.result_file_id, safe='')}/content")
+ if state.error is not None:
+ file["error"] = state.error.model_dump()
files.append(file)
- if item.url is None and upload is None and record.status == "waiting_upload":
+ if (
+ item.url is None
+ and state.status == "waiting_upload"
+ and record.status != "canceled"
+ and record.expires_at > time.time()
+ ):
links.append(
{
"client_file_id": item.client_file_id,
@@ -665,60 +765,43 @@ def task_payload(record: _TaskRecord, request: Request) -> dict[str, Any]:
"expires_at": record.expires_at,
}
)
- result_id = record.execution.result_file_id if record.execution is not None else None
payload = {
"task_id": record.id,
"status": record.status,
"status_url": _url(request, f"/v1/tasks/{record.id}"),
- "result_url": _url(request, f"/v1/files/{quote(result_id, safe='')}/content")
- if result_id and record.status in {"completed", "partial"}
- else None,
"created_at": record.created_at,
- "started_at": job.get("started_at"),
+ "started_at": min(starts) if starts else None,
"finished_at": record.finished_at,
- "tier": job.get("tier") or record.options.tier,
+ "tier": record.options.tier,
"output_formats": record.options.output_formats,
- "progress": job.get("progress") or {"completed": 0, "failed": 0, "total": len(files)},
+ "progress": {
+ "completed": sum(file.status == "completed" for file in record.files),
+ "failed": sum(file.status == "failed" for file in record.files),
+ "total": len(files),
+ },
"files": files,
"uploads": links,
- "error": record.error.model_dump() if record.error is not None else None,
+ "error": record.error.model_dump() if record.error else None,
}
return TaskStatusResponse.model_validate(payload).model_dump()
def _request_schema() -> dict[str, Any]:
- """明确记录表单字段和单文件约束,不再暴露查询参数或旧内容类型。"""
- properties = UploadTaskOptions.model_json_schema()["properties"]
- # 清单使用 JSON 文本表单字段,客户端无需发送 application/json 请求。
- properties["manifest"] = {
- "type": "string",
- "description": (
- "JSON array of 1-100 files: client_file_id, filename, optional url, sha256sum and page_range. "
- "bytes must be a positive integer for uploads; it is optional/null for URL inputs. "
- "URL inputs have upload_status=not_required and never receive upload links."
- ),
- "example": '[{"client_file_id":"f1","filename":"document.pdf","bytes":12345}]',
- }
- plain = {"type": "object", "required": ["manifest"], "additionalProperties": False, "properties": properties}
- multipart = copy.deepcopy(plain)
- multipart.pop("required")
- multipart["anyOf"] = [{"required": ["manifest"]}, {"required": ["files"]}]
- multipart["properties"]["files"] = {
- "type": "array",
- "minItems": 1,
- "maxItems": 1,
- "items": {"type": "string", "format": "binary"},
- "description": ("Local single-file direct upload only; a supplied manifest must contain exactly one file without url."),
- }
- return {
- "requestBody": {
- "required": True,
- "content": {
- "application/x-www-form-urlencoded": {"schema": plain},
- "multipart/form-data": {"schema": multipart},
- },
- }
- }
+ """OpenAPI 使用与运行时相同的 JSON 清单和格式约束。"""
+ schema = CreateTaskRequest.model_json_schema()
+ definitions = schema.pop("$defs", {})
+
+ def expand(value: Any) -> Any:
+ """内联局部模型引用,避免 OpenAPI 把 JSON Schema 的 $defs 当成全局路径。"""
+ if isinstance(value, dict):
+ if "$ref" in value:
+ return expand(definitions[value["$ref"].rsplit("/", 1)[-1]])
+ return {key: expand(item) for key, item in value.items()}
+ if isinstance(value, list):
+ return [expand(item) for item in value]
+ return value
+
+ return {"requestBody": {"required": True, "content": {"application/json": {"schema": expand(schema)}}}}
def build_task_router(factory: Callable[[Request], TaskBackend]) -> APIRouter:
@@ -727,13 +810,12 @@ def build_task_router(factory: Callable[[Request], TaskBackend]) -> APIRouter:
@router.post("/tasks", status_code=202, response_model=TaskStatusResponse, openapi_extra=_request_schema())
async def create_task(request: Request) -> Response:
- """先验证表单再建立稳定任务 ID,HTTP 结束后后台工作独立继续。"""
+ """先验证 JSON 再建立稳定任务 ID,HTTP 结束后逐文件工作独立继续。"""
backend = factory(request)
store: TaskStore = request.app.state.task_store
try:
- with tempfile.TemporaryDirectory(prefix="mineru-task-request-") as temporary:
- options, manifest, direct = await _read_submission(request, Path(temporary))
- record = await store.create(backend, options, manifest, direct)
+ options, manifest = await _read_submission(request)
+ record = await store.create(backend, options, manifest, lease_seconds=_retention_lease(request) or 0)
except BaseException:
backend.release_uploads(rollback=True)
raise
@@ -741,9 +823,10 @@ def build_task_router(factory: Callable[[Request], TaskBackend]) -> APIRouter:
@router.get("/tasks/{task_id}", response_model=TaskStatusResponse)
async def get_task(task_id: str, request: Request) -> Response:
- """读取上传准备与后台状态,成功时返回可直接下载的 ZIP 地址。"""
+ """读取逐文件状态与结果地址,上传链接截止时间保持不变。"""
store: TaskStore = request.app.state.task_store
record = store.lookup(task_id, factory(request).owner_scope)
+ store.update_lease(record, _retention_lease(request))
await store.refresh(record)
return JSONResponse(task_payload(record, request))
@@ -758,10 +841,14 @@ def build_task_router(factory: Callable[[Request], TaskBackend]) -> APIRouter:
},
)
async def upload_task_file(task_id: str, client_file_id: str, request: Request) -> Response:
- """每条上传链接只接受一个文件,最后一个文件就绪后自动提交。"""
+ """每条上传链接只接收一个文件,该文件就绪后立即提交执行。"""
store: TaskStore = request.app.state.task_store
record = store.lookup(task_id, factory(request).owner_scope)
+ lease_seconds = _retention_lease(request)
+ store.update_lease(record, lease_seconds)
skipped = await store.upload(record, client_file_id, request)
+ # 大文件转传可超过租约长度;受理完成时续租,保护紧接着发布的结果。
+ store.update_lease(record, lease_seconds)
return JSONResponse(
task_payload(record, request),
headers={"Connection": "close"} if skipped and request.scope.get("http_version") == "1.1" else None,
@@ -779,59 +866,11 @@ def build_task_router(factory: Callable[[Request], TaskBackend]) -> APIRouter:
return router
-def _combine_archives(store: FileStore, job: _JobRecord, path: Path, manifest: list[TaskManifestItem], status: str) -> str:
- """在后台流式构建批量 ZIP,固定输入顺序并拒绝越界成员路径。"""
- snapshot = {
- "status": status,
- # ZIP 可独立消费;不把 worker 的私有 task/file ID 或短期下载地址写入产物。
- "files": [
- {
- **item.model_dump(exclude={"url"}),
- **(
- {"bytes": job.input_metadata[index].bytes, "sha256sum": job.input_metadata[index].sha256sum}
- if index in job.input_metadata
- else {}
- ),
- "name": result.name,
- "page_range": result.page_range,
- "status": result.status,
- "directory": f"{index + 1:04d}/" if result.status == "completed" else None,
- "parse": result.parse.model_dump() if result.parse is not None else None,
- "error": result.error.model_dump() if result.error is not None else None,
- }
- for index, (item, result) in enumerate(zip(manifest, job.files))
- ],
- }
- with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED, allowZip64=True) as target:
- target.writestr("manifest.json", json.dumps(snapshot, ensure_ascii=False))
- for index, file in enumerate(job.files):
- if file.status != "completed":
- continue
- if file.output_files is None or file.output_files.zip is None:
- raise ValueError("ZIP output is missing")
- source_path, _, sha = store.pin_output_file(file.output_files.zip.file_id)
- try:
- with zipfile.ZipFile(source_path) as source:
- for info in source.infolist():
- member = Path(info.filename)
- if member.is_absolute() or ".." in member.parts or "\\" in info.filename:
- raise ValueError("Invalid ZIP member path")
- name = f"{index + 1:04d}/{info.filename}"
- if info.is_dir():
- target.writestr(name, b"")
- else:
- with source.open(info) as incoming, target.open(name, "w", force_zip64=True) as outgoing:
- shutil.copyfileobj(incoming, outgoing, length=1024 * 1024)
- finally:
- store.unpin_cached_blob(sha)
- return store.create_file_for_output_path(f"{job.id}.zip", path, job_id=job.id)
-
-
class ApiTaskBackend:
"""把上传准备接入 API server 的唯一文件存储和 JobStore。"""
def __init__(self, request: Request) -> None:
- """保留轻量请求上下文,避免跨请求持有已解析的表单和上传对象。"""
+ """保留轻量请求上下文,不跨请求持有上传主体。"""
self.request = Request(dict(request.scope))
self.files: FileStore = request.app.state.file_store
self.jobs: JobStore = request.app.state.job_store
@@ -840,6 +879,14 @@ class ApiTaskBackend:
self._pins: list[str] = []
self._owned_files: list[str] = []
+ def fork(self) -> ApiTaskBackend:
+ """为单个文件隔离源字节引用,其他文件提交不释放本文件资源。"""
+ return ApiTaskBackend(self.request)
+
+ async def release_result(self, task_id: str, finished: float) -> None:
+ """由父 Task 统一开始子作业与结果文件的保留期。"""
+ self.jobs.release_task_result(task_id, finished)
+
async def validate(self, options: UploadTaskOptions, manifest: list[TaskManifestItem]) -> None:
"""复用引擎就绪状态,提前校验显式 tier 与轻量格式能力。"""
_require_model_preload_ready(self.request)
@@ -896,7 +943,7 @@ class ApiTaskBackend:
async def submit(
self, task_id: str, options: UploadTaskOptions, manifest: list[TaskManifestItem], uploads: dict[int, TaskUpload]
) -> TaskExecution:
- """把已上传文件和 URL 来源交给现有队列,在发布成功前完成最终 ZIP。"""
+ """提交单文件子作业,在同一次解析中生成专用产物并持有结果租约。"""
# 接单时已持有源字节;用户删除文件视图也不能破坏尚在等待其他文件的任务。
for upload in uploads.values():
await run_sync(
@@ -912,36 +959,9 @@ class ApiTaskBackend:
],
tier=options.tier,
ocr_mode=options.ocr_mode,
- output_formats=options.output_formats,
+ output_formats=[],
)
- async def finalize(job: _JobRecord) -> None:
- """打包保持 running,失败与取消均不能发布一个不可用的下载链接。"""
- terminal = job.status
- job.status = "running"
- job.finished_at = None
- try:
- if len(job.files) == 1:
- output = job.files[0].output_files
- if output is None or output.zip is None:
- raise ValueError("ZIP output is missing")
- file_id = output.zip.file_id
- else:
- with tempfile.TemporaryDirectory(prefix="mineru-task-zip-") as directory:
- file_id = await run_sync(
- _combine_archives, self.files, job, Path(directory) / "result.zip", manifest, terminal
- )
- if job.status not in {"canceled", "failed"}:
- job.task_result_file_id = file_id
- job.status = terminal
- except asyncio.CancelledError:
- raise
- except Exception as exc:
- if job.status != "canceled":
- job.task_error = ErrorDetail(type="api_error", code="result_packaging_failed", message=str(exc))
- job.status = "failed"
- logger.exception("Task ZIP creation failed: %s", task_id)
-
await submit_parse_job(
body,
self.request,
@@ -949,7 +969,7 @@ class ApiTaskBackend:
self.jobs,
self.access,
job_id=task_id,
- finalize=finalize,
+ task_output_formats=options.output_formats,
input_specs={
index: _JobInputSpec(item.filename, item.bytes, item.sha256sum) for index, item in enumerate(manifest)
},
@@ -962,13 +982,15 @@ class ApiTaskBackend:
return TaskExecution(
self.jobs.build_response(record, access_level=self.access).model_dump(by_alias=True),
record.task_result_file_id,
- record.task_error,
+ None,
dict(record.input_metadata),
)
async def cancel(self, task_id: str) -> None:
"""沿用 JobStore 取消及线程清理边界,终态竞争不影响已经完成的任务。"""
- record = self.jobs.get(task_id)
+ record = self.jobs._jobs.get(task_id)
+ if record is None:
+ return
if record.status not in TERMINAL_TASK_STATUSES:
self.jobs.cancel(task_id)
await self.jobs.wait_for_terminal(task_id, 3600)
@@ -976,6 +998,7 @@ class ApiTaskBackend:
__all__ = [
"ApiTaskBackend",
+ "CreateTaskRequest",
"TaskBackend",
"TaskExecution",
"TaskManifestItem",
diff --git a/mineru/parser/task_outputs.py b/mineru/parser/task_outputs.py
new file mode 100644
index 00000000..b66894a0
--- /dev/null
+++ b/mineru/parser/task_outputs.py
@@ -0,0 +1,59 @@
+"""Tasks 专用产物策略:每个输入只发布一个完整的可下载文件。"""
+
+from __future__ import annotations
+
+import json
+import zipfile
+from pathlib import Path
+from typing import Literal
+
+from .base import ParseResult
+
+TaskOutputFormat = Literal["default", "docx", "html", "latex"]
+TASK_OUTPUT_FORMATS: tuple[TaskOutputFormat, ...] = ("default", "docx", "html", "latex")
+
+
+def build_task_output(result: ParseResult, formats: list[TaskOutputFormat], directory: Path) -> Path:
+ """一次物化并渲染所选格式,全部成功后才返回主产物路径。"""
+ from docvortex.export import embed_html_images, materialize_middle, validate_materialized_assets
+
+ from ..render import render_docx, render_html, render_latex
+
+ middle, assets = materialize_middle(result.middle_json)
+ validate_materialized_assets(middle, assets)
+ exported = ParseResult(middle_json=middle)
+ entries: dict[str, bytes] = {}
+ if "default" in formats:
+ entries.update(
+ {
+ "markdown.md": exported.markdown().encode("utf-8", errors="replace"),
+ "middle_json.json": exported.to_json().encode("utf-8", errors="replace"),
+ "structured_content.json": json.dumps(exported.structured_content(), ensure_ascii=False, indent=2).encode(
+ "utf-8", errors="replace"
+ ),
+ }
+ )
+ if "docx" in formats:
+ entries["document.docx"] = render_docx(middle, asset_resolver=assets.__getitem__)
+ if "html" in formats:
+ entries["document.html"] = embed_html_images(render_html(middle), assets).encode("utf-8", errors="replace")
+ if "latex" in formats:
+ entries["document.tex"] = render_latex(middle).encode("utf-8", errors="replace")
+ directory.mkdir(parents=True, exist_ok=True)
+ if len(formats) == 1 and formats[0] in {"docx", "html"}:
+ name, content = next(iter(entries.items()))
+ target = directory / name
+ target.write_bytes(content)
+ return target
+ target = directory / "result.zip"
+ with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED, allowZip64=True) as archive:
+ for name, content in entries.items():
+ archive.writestr(name, content)
+ if "default" in formats or "latex" in formats:
+ archive.writestr("images/", b"")
+ for name, content in sorted(assets.items()):
+ archive.writestr(name, content)
+ return target
+
+
+__all__ = ["TASK_OUTPUT_FORMATS", "TaskOutputFormat", "build_task_output"]
diff --git a/pyproject.toml b/pyproject.toml
index 0dd2aba7..65e4a24d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -38,7 +38,7 @@ classifiers = [
"Programming Language :: Python :: 3.14",
]
dependencies = [
- "docvortex>=0.5.16,<1",
+ "docvortex>=0.5.17,<1",
"gradio>=6.8,<7",
"mineru[torch] ; sys_platform == 'darwin' and platform_machine == 'arm64'",
"mineru-vl-utils>=2.0.7,<3",
diff --git a/scripts/http_task_example.py b/scripts/http_task_example.py
index 410d9679..e6ae9c22 100644
--- a/scripts/http_task_example.py
+++ b/scripts/http_task_example.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-"""仅使用 Python 标准库的 tasks HTTP 示例:清单、逐文件上传、轮询与 ZIP 下载。"""
+"""仅使用 Python 标准库的 tasks HTTP 示例:JSON 清单、逐文件上传、轮询与独立结果下载。"""
from __future__ import annotations
@@ -7,7 +7,6 @@ import hashlib
import http.client
import json
import os
-import secrets
import socket
import sys
import tempfile
@@ -18,7 +17,7 @@ from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Any
-from urllib.parse import quote, urlencode, urljoin, urlsplit
+from urllib.parse import quote, urljoin, urlsplit
TERMINAL = frozenset({"completed", "partial", "failed", "canceled"})
STATUSES = TERMINAL | {"waiting_upload", "queued", "running"}
@@ -49,7 +48,7 @@ class InputFile:
sha256sum: str | None
def manifest(self) -> dict[str, Any]:
- """生成表单清单条目;关闭 hash 时完全省略该可选字段。"""
+ """生成 JSON 清单条目;关闭 hash 时完全省略该可选字段。"""
item: dict[str, Any] = {"client_file_id": self.client_file_id, "filename": self.path.name, "bytes": self.size}
if self.sha256sum is not None:
item["sha256sum"] = self.sha256sum
@@ -67,7 +66,7 @@ def _file_body(path: Path) -> Generator[bytes, None, None]:
def _bytes_body(data: bytes) -> Generator[bytes, None, None]:
- """为小型表单主体提供可重新创建的发送迭代器。"""
+ """为小型 JSON 主体提供可重新创建的发送迭代器。"""
yield data
@@ -115,6 +114,7 @@ class TaskClient:
raise ClientError("POLL_INTERVAL must be a non-negative finite number")
self.task_id: str | None = None
self.status_url: str | None = None
+ self.saved_ids: set[str] = set()
def resolve(self, url: str) -> str:
"""解析服务返回的绝对或相对链接,保留 OSS 签名查询串。"""
@@ -215,7 +215,7 @@ class TaskClient:
if data is not None:
def data_body() -> Generator[bytes, None, None]:
- """闭包固定本次表单字节,避免把文件内容放进 JSON 请求。"""
+ """闭包固定本次 JSON 元数据字节,不把源文件主体放入创建请求。"""
yield from _bytes_body(data)
body, length = data_body, len(data)
@@ -258,7 +258,7 @@ class TaskClient:
raise ClientError("Task manifest differs from local inputs; use the original file list and order")
if local.sha256sum is not None and item.get("sha256sum") not in {None, local.sha256sum}:
raise ClientError("Task hash differs from the local file")
- if item.get("upload_status") not in {"pending", "ready"}:
+ if item.get("upload_status") not in {"pending", "ready", "expired"}:
raise ClientError("Unknown upload_status")
uploads = payload.get("uploads")
if not isinstance(uploads, list):
@@ -276,68 +276,47 @@ class TaskClient:
raise ClientError("Invalid upload URL or method")
if not isinstance(link.get("upload_headers"), dict):
raise ClientError("Invalid upload headers")
- if payload["status"] == "waiting_upload":
- if seen_uploads != pending:
- raise ClientError("Upload descriptors do not match pending files")
- elif seen_uploads:
- raise ClientError("Task no longer accepts uploads but still returns upload URLs")
- if payload["status"] in {"queued", "running", "completed", "partial"} and pending:
- raise ClientError("Task started before all files became ready")
- if payload["status"] in {"completed", "partial"}:
- if not isinstance(payload.get("result_url"), str) or not payload["result_url"]:
- raise ClientError("Completed task has no ZIP download URL")
+ if not seen_uploads.issubset(pending):
+ raise ClientError("Upload descriptors do not match pending files")
+ if payload["status"] in TERMINAL and seen_uploads:
+ raise ClientError("Terminal task still returns upload URLs")
+ formats = payload.get("output_formats")
+ if (
+ not isinstance(formats, list)
+ or not formats
+ or any(value not in {"default", "docx", "html", "latex"} for value in formats)
+ ):
+ raise ClientError("Invalid task output_formats")
+ for item in files:
+ if item.get("status") not in {"waiting_upload", "queued", "running", "completed", "failed", "canceled"}:
+ raise ClientError("Unknown file status")
+ if item["status"] == "completed":
+ if not isinstance(item.get("result_url"), str) or not item["result_url"]:
+ raise ClientError("Completed file has no download URL")
+ elif item.get("result_url") is not None:
+ raise ClientError("Unfinished file has a download URL")
self.task_id = task_id
self.status_url = self.resolve(payload["status_url"])
return payload
- def _form(self) -> list[tuple[str, str]]:
- """所有解析参数都编码到表单,包括 JSON 文本形式的 manifest。"""
- values = [
- ("manifest", json.dumps([file.manifest() for file in self.files], ensure_ascii=False)),
- ("ocr_mode", os.environ.get("OCR_MODE", "auto")),
- ("page_range", os.environ.get("PAGE_RANGE", "")),
- ]
+ def create(self) -> dict[str, Any]:
+ """用一次 JSON 请求创建清单,文件主体只发送到服务返回的上传链接。"""
+ formats = [value.strip() for value in os.environ.get("OUTPUT_FORMATS", "default").split(",")]
+ if not formats or any(value not in {"default", "docx", "html", "latex"} for value in formats):
+ raise ClientError("OUTPUT_FORMATS must contain default/docx/html/latex")
+ body: dict[str, Any] = {
+ "manifest": [file.manifest() for file in self.files],
+ "ocr_mode": os.environ.get("OCR_MODE", "auto"),
+ "page_range": os.environ.get("PAGE_RANGE", ""),
+ "output_formats": list(dict.fromkeys(formats)),
+ }
if os.environ.get("MINERU_TIER"):
- values.append(("tier", os.environ["MINERU_TIER"]))
- formats = [value.strip() for value in os.environ.get("OUTPUT_FORMATS", "markdown").split(",")]
- if not all(formats):
- raise ClientError("OUTPUT_FORMATS contains an empty entry")
- values.extend(("output_formats", value) for value in dict.fromkeys([*formats, "zip"]))
- return values
-
- def create(self, mode: str) -> dict[str, Any]:
- """创建只执行一次;单文件直传也返回异步任务,不等待服务端同步解析。"""
- values = self._form()
- if mode == "preflight":
- return self.json_request(
- "POST",
- self.base + "/v1/tasks",
- data=urlencode(values).encode(),
- headers={"Content-Type": "application/x-www-form-urlencoded"},
- )
- boundary = "mineru-" + secrets.token_hex(16)
- prefix = bytearray()
- for name, value in values:
- prefix.extend(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode())
- # 逻辑文件名来自 manifest;固定 part 文件名避免引号、换行等字符破坏 MIME 头。
- prefix.extend(
- f'--{boundary}\r\nContent-Disposition: form-data; name="files"; filename="upload.bin"\r\n'
- "Content-Type: application/octet-stream\r\n\r\n".encode()
- )
- suffix = f"\r\n--{boundary}--\r\n".encode()
-
- def multipart_body() -> Generator[bytes, None, None]:
- """只在内存保留小型表单元数据,文件主体仍从磁盘分块发送。"""
- yield bytes(prefix)
- yield from _file_body(self.files[0].path)
- yield suffix
-
+ body["tier"] = os.environ["MINERU_TIER"]
return self.json_request(
"POST",
self.base + "/v1/tasks",
- body=multipart_body,
- length=len(prefix) + self.files[0].size + len(suffix),
- headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
+ data=json.dumps(body, ensure_ascii=False).encode(),
+ headers={"Content-Type": "application/json"},
)
def refresh(self) -> dict[str, Any]:
@@ -381,15 +360,15 @@ class TaskClient:
raise self._http_error(response)
break
except ClientError as exc:
- if not exc.retryable and exc.status != 403:
+ if not exc.retryable and exc.status not in {403, 410}:
raise
# 请求可能已经落盘但响应丢失;先看状态,再决定是否重传。
current = self.refresh_after_transfer_error()
remote = next(item for item in current["files"] if item["client_file_id"] == client_id)
if remote["upload_status"] == "ready":
break
- if current["status"] != "waiting_upload":
- return current
+ if remote["status"] in {"failed", "canceled"}:
+ break
replacement = next((item for item in current["uploads"] if item["client_file_id"] == client_id), None)
if replacement is None:
raise ClientError("Pending file has no upload URL") from exc
@@ -401,13 +380,13 @@ class TaskClient:
time.sleep(attempt + 1)
return self.refresh()
- def download(self, task: dict[str, Any], output: Path) -> None:
- """只访问返回的 ZIP 链接,支持过期链接刷新和安全的跨源重定向。"""
+ def download(self, task: dict[str, Any], file: dict[str, Any], output: Path) -> None:
+ """下载一个已完成文件,按所选格式校验,并安全刷新过期下载链接。"""
output.parent.mkdir(parents=True, exist_ok=True)
descriptor, name = tempfile.mkstemp(prefix=output.name + ".", suffix=".part", dir=output.parent)
os.close(descriptor)
temporary = Path(name)
- url = self.resolve(task["result_url"])
+ url = self.resolve(file["result_url"])
try:
for attempt in range(3):
try:
@@ -426,24 +405,35 @@ class TaskClient:
try:
target.write(chunk)
except OSError as exc:
- raise ClientError(f"Cannot save ZIP: {exc}") from exc
+ raise ClientError(f"Cannot save result: {exc}") from exc
expected = response.getheader("Content-Length")
if expected is not None and temporary.stat().st_size != int(expected):
- raise ClientError("Incomplete ZIP download", retryable=True)
+ raise ClientError("Incomplete result download", retryable=True)
break
else:
raise ClientError("Too many download redirects")
- if not zipfile.is_zipfile(temporary):
- raise ClientError("Downloaded result is not a ZIP archive")
+ formats = list(dict.fromkeys(task["output_formats"]))
+ if formats == ["html"]:
+ if "<html" not in temporary.read_text(encoding="utf-8").lower():
+ raise ClientError("Downloaded result is not an HTML document")
+ else:
+ if not zipfile.is_zipfile(temporary):
+ raise ClientError("Downloaded result is not a ZIP archive")
+ with zipfile.ZipFile(temporary) as archive:
+ if archive.testzip() is not None:
+ raise ClientError("Downloaded ZIP is corrupt")
+ if formats == ["docx"] and "word/document.xml" not in archive.namelist():
+ raise ClientError("Downloaded result is not a DOCX document")
temporary.replace(output)
return
except ClientError as exc:
if attempt == 2 or (not exc.retryable and exc.status not in {401, 403, 404}):
raise
current = self.refresh_after_transfer_error()
- if current["status"] not in {"completed", "partial"}:
- raise ClientError("Task no longer has a downloadable result") from exc
- replacement = self.resolve(current["result_url"])
+ remote = next(item for item in current["files"] if item["client_file_id"] == file["client_file_id"])
+ if remote["status"] != "completed":
+ raise ClientError("File no longer has a downloadable result") from exc
+ replacement = self.resolve(remote["result_url"])
if exc.status in {401, 403, 404} and replacement == url:
raise
url = replacement
@@ -451,18 +441,36 @@ class TaskClient:
finally:
temporary.unlink(missing_ok=True)
- def run(self, mode: str, output: Path) -> int:
- """一条命令等待异步任务并保存 ZIP,超时保留任务供后续恢复。"""
+ def download_completed(self, task: dict[str, Any], output: Path) -> None:
+ """按 client_file_id 保存独立结果,同名输入和多次轮询不会相互覆盖。"""
+ formats = list(dict.fromkeys(task["output_formats"]))
+ extension = formats[0] if len(formats) == 1 and formats[0] in {"html", "docx"} else "zip"
+ for file in task["files"]:
+ client_id = file["client_file_id"]
+ if file["status"] != "completed" or client_id in self.saved_ids:
+ continue
+ destination = output / client_id / (self.by_id[client_id].path.stem + "." + extension)
+ self.download(task, file, destination)
+ self.saved_ids.add(client_id)
+ print(f"Saved {destination}")
+
+ def run(self, output: Path) -> int:
+ """上传缺失文件并逐个下载成功结果,失败与取消也保留已经完成的产物。"""
resume = os.environ.get("TASK_ID", "")
if resume:
self.task_id = resume
self.status_url = self.base + "/v1/tasks/" + quote(resume, safe="")
task = self.refresh()
else:
- task = self.create(mode)
+ task = self.create()
print(f"task_id={self.task_id}", file=sys.stderr)
- if task["status"] == "waiting_upload":
- task = self.upload_missing(task)
+ self.download_completed(task, output)
+ for link in list(task["uploads"]):
+ current_links = [item for item in task["uploads"] if item["client_file_id"] == link["client_file_id"]]
+ if not current_links:
+ continue
+ task = self.upload_missing({**task, "uploads": current_links})
+ self.download_completed(task, output)
polls = 0
while task["status"] not in TERMINAL:
if polls >= self.max_polls:
@@ -475,14 +483,14 @@ class TaskClient:
except ClientError as exc:
if not exc.retryable:
raise
+ continue
+ self.download_completed(task, output)
if task["status"] in {"failed", "canceled"}:
print(
json.dumps({"status": task["status"], "error": task.get("error"), "files": task["files"]}, ensure_ascii=False),
file=sys.stderr,
)
return 1
- self.download(task, output)
- print(f"Saved {output}")
return 2 if task["status"] == "partial" else 0
@@ -492,11 +500,8 @@ def main(arguments: list[str]) -> int:
try:
if not arguments:
raise ClientError("usage: bash scripts/http_task_example.sh <file> [file ...]")
- mode = os.environ.get("UPLOAD_MODE", "preflight")
- if mode not in {"preflight", "direct"}:
- raise ClientError("UPLOAD_MODE must be preflight or direct")
- if mode == "direct" and len(arguments) != 1:
- raise ClientError("Direct multipart upload accepts one file; use preflight for multiple files")
+ if os.environ.get("UPLOAD_MODE") or os.environ.get("RESULT_FILE"):
+ raise ClientError("UPLOAD_MODE and RESULT_FILE were removed; use JSON preflight and RESULT_DIR")
send_hash = os.environ.get("SEND_HASH", "1")
if send_hash not in {"0", "1"}:
raise ClientError("SEND_HASH must be 0 or 1")
@@ -511,7 +516,7 @@ def main(arguments: list[str]) -> int:
hasher.update(chunk)
inputs.append(InputFile(path, f"f{index + 1}", path.stat().st_size, hasher.hexdigest() if hasher else None))
client = TaskClient(inputs)
- return client.run(mode, Path(os.environ.get("RESULT_FILE", "result.zip")))
+ return client.run(Path(os.environ.get("RESULT_DIR", "results")))
except (ClientError, OSError, ValueError) as exc:
print(f"error: {exc}", file=sys.stderr)
if client is not None and client.task_id:
diff --git a/scripts/http_task_example.sh b/scripts/http_task_example.sh
index 9c0f6084..11b6633c 100644
--- a/scripts/http_task_example.sh
+++ b/scripts/http_task_example.sh
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
-# tasks HTTP 示例:默认预检后逐文件上传,轮询状态并下载服务返回的 ZIP 链接。
-# SEND_HASH=0 可省略 hash;TASK_ID=... 恢复原任务;UPLOAD_MODE=direct 仅允许单文件。
+# tasks HTTP 示例:默认预检后逐文件上传,轮询并逐文件保存结果到 RESULT_DIR。
+# SEND_HASH=0 可省略 hash;TASK_ID=... 恢复原任务;每个输入都先通过 JSON 清单预检。
# 成功退出 0,部分成功退出 2,失败退出 1,轮询预算耗尽退出 124。
set -euo pipefail
TASK_SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
diff --git a/tests/unittest/test_resource_retention.py b/tests/unittest/test_resource_retention.py
index f2293ee6..6971defe 100644
--- a/tests/unittest/test_resource_retention.py
+++ b/tests/unittest/test_resource_retention.py
@@ -4,7 +4,6 @@ from __future__ import annotations
import asyncio
import hashlib
-import json
import os
from datetime import datetime, timezone
from pathlib import Path
@@ -240,13 +239,9 @@ def test_hash_preflight_rejection_releases_request_lease(tmp_path: Path, monkeyp
_, sha = _source(app.state.file_store, tmp_path)
response = client.post(
"/v1/tasks",
- data={
+ json={
"tier": "flash",
- "manifest": json.dumps(
- [
- {"client_file_id": "f1", "filename": "input.pdf", "bytes": 3, "sha256sum": sha},
- ]
- ),
+ "manifest": [{"client_file_id": "f1", "filename": "input.pdf", "bytes": 3, "sha256sum": sha}],
},
)
assert response.status_code == 400
diff --git a/tests/unittest/test_router_balancing.py b/tests/unittest/test_router_balancing.py
index 7b4f1488..3d8032c2 100644
--- a/tests/unittest/test_router_balancing.py
+++ b/tests/unittest/test_router_balancing.py
@@ -3,7 +3,6 @@
from __future__ import annotations
import asyncio
-import json
import threading
import time
from pathlib import Path
@@ -62,7 +61,7 @@ def test_task_auth_preflight_uses_a_capable_worker_without_reservation() -> None
if request.url.path == "/v1/health":
response = await (first if request.url.host == "worker-a" else second).handle(request)
payload = response.json()
- payload["features"]["output_formats"].append("zip")
+ payload["features"]["task_output_formats"] = ["default", "docx", "html", "latex"]
return httpx.Response(200, json=payload, request=request)
if request.url.path == "/v1/files":
checked.append(request.url.host)
@@ -89,20 +88,18 @@ def test_task_auth_preflight_uses_a_capable_worker_without_reservation() -> None
)
form = {
"tier": "standard",
- "manifest": json.dumps(
- [
- {
- "client_file_id": "f1",
- "filename": "source.pdf",
- "bytes": 3,
- }
- ]
- ),
+ "manifest": [
+ {
+ "client_file_id": "f1",
+ "filename": "source.pdf",
+ "bytes": 3,
+ }
+ ],
}
with TestClient(app) as client:
cursors = dict(app.state.worker_pool._selection_cursors)
- assert client.post("/v1/tasks", data=form).status_code == 401
- accepted = client.post("/v1/tasks", data=form, headers={"authorization": "Bearer owner"})
+ assert client.post("/v1/tasks", json=form).status_code == 401
+ accepted = client.post("/v1/tasks", json=form, headers={"authorization": "Bearer owner"})
assert accepted.status_code == 202, accepted.text
assert checked == ["worker-b", "worker-b"]
assert app.state.worker_pool._selection_cursors == cursors
@@ -212,7 +209,7 @@ def test_cached_tasks_still_balance(tmp_path: Path, monkeypatch: pytest.MonkeyPa
assert task["uploads"] == []
tasks.append(task)
deadline = time.monotonic() + 5
- while not app.state.task_store._records[task["task_id"]].submitted:
+ while not app.state.task_store._records[task["task_id"]].files[0].submitted:
assert time.monotonic() < deadline
time.sleep(0.01)
assert [worker.active_jobs for worker in app.state.worker_pool.workers] == [5, 5]
@@ -378,7 +375,7 @@ def test_task_submission_failure_and_replacement_release_only_owned_load(
task = _submit(client, [("source.html", HTML)])
_upload(client, task, [("source.html", HTML)])
failed = _terminal(client, task)
- assert failed["status"] == "failed" and failed["result_url"] is None
+ assert failed["status"] == "failed" and failed["files"][0]["result_url"] is None
assert not app.state.registry.list("job")
assert not app.state.source_store._files and not app.state.source_store._uploads
assert app.state.worker_pool.workers[0].active_jobs == (1 if replacement else 0)
diff --git a/tests/unittest/test_task_api.py b/tests/unittest/test_task_api.py
index 8f40de0f..e07e2917 100644
--- a/tests/unittest/test_task_api.py
+++ b/tests/unittest/test_task_api.py
@@ -116,7 +116,7 @@ def _submit(
headers: dict[str, str] | None = None,
**options: str | list[str],
) -> dict[str, Any]:
- """只用表单提交真实大小及可选 SHA-256,绝不在创建请求中发送多个文件。"""
+ """只用 JSON 提交真实大小及可选 SHA-256,绝不在创建请求中发送多个文件。"""
manifest = [
{
"client_file_id": f"f{index + 1}",
@@ -126,7 +126,7 @@ def _submit(
}
for index, (name, data) in enumerate(inputs)
]
- response = client.post("/v1/tasks", data={"manifest": json.dumps(manifest), "tier": "flash", **options}, headers=headers)
+ response = client.post("/v1/tasks", json={"manifest": manifest, "tier": "flash", **options}, headers=headers)
assert response.status_code == 202, response.text
return response.json()
@@ -144,7 +144,7 @@ def _upload(
def _terminal(client: TestClient, task: dict[str, Any], *, headers: dict[str, str] | None = None) -> dict[str, Any]:
- """只轮询状态接口;成功前必须一直没有 result_url。"""
+ """只轮询状态接口;未完成的文件不能发布 result_url。"""
deadline = time.monotonic() + 20
while time.monotonic() < deadline:
response = client.get(task["status_url"], headers=headers)
@@ -152,15 +152,26 @@ def _terminal(client: TestClient, task: dict[str, Any], *, headers: dict[str, st
payload = response.json()
if payload["status"] in task_api.TERMINAL_TASK_STATUSES:
return payload
- assert payload["result_url"] is None
+ assert all(file["result_url"] is None for file in payload["files"] if file["status"] != "completed")
time.sleep(0.01)
pytest.fail("Task did not reach a terminal state")
-def _archive(client: TestClient, task: dict[str, Any]) -> dict[str, bytes]:
+def _file_done(client: TestClient, task: dict[str, Any], index: int) -> dict[str, Any]:
+ """只等待指定文件完成,父任务可继续等待其他上传。"""
+ deadline = time.monotonic() + 20
+ while time.monotonic() < deadline:
+ payload = client.get(task["status_url"]).json()
+ if payload["files"][index]["status"] in {"completed", "failed", "canceled"}:
+ return payload
+ time.sleep(0.01)
+ pytest.fail("File did not finish")
+
+
+def _archive(client: TestClient, task: dict[str, Any], index: int = 0) -> dict[str, bytes]:
"""从返回的独立 Files 链接下载并读取真实 ZIP 成员。"""
- assert "/v1/files/" in task["result_url"]
- response = client.get(task["result_url"])
+ assert "/v1/files/" in task["files"][index]["result_url"]
+ response = client.get(task["files"][index]["result_url"])
assert response.status_code == 200, response.text
assert response.headers["content-type"] == "application/zip"
with zipfile.ZipFile(io.BytesIO(response.content)) as archive:
@@ -176,84 +187,45 @@ def _job_count(app: FastAPI) -> int:
@pytest.mark.parametrize("hashes", [False, True])
def test_manifest_uploads_and_zip_only_status(service: tuple[TestClient, FastAPI], hashes: bool) -> None:
- """单文件与批量都经过共同协议,状态只给元数据,ZIP 保留输入次序。"""
+ """先上传文件立即执行并可下载,同名文件通过客户端标识保持独立。"""
client, app = service
inputs = [("同名 文档.html", HTML), ("同名 文档.html", SECOND)]
- task = _submit(client, inputs, hashes=hashes, output_formats=["markdown", "middle_json"])
- assert task["status"] == "waiting_upload" and task["result_url"] is None
+ task = _submit(client, inputs, hashes=hashes, output_formats=["default"])
+ assert task["status"] == "waiting_upload" and "result_url" not in task
assert len(task["uploads"]) == 2 and _job_count(app) == 0
- if hasattr(app.state, "worker_pool"):
- assert [worker.active_jobs for worker in app.state.worker_pool.workers] == [0, 0]
- first = client.put(task["uploads"][0]["upload_url"], content=HTML)
- assert first.status_code == 200
- ready = client.get(task["status_url"]).json()
+ assert client.put(task["uploads"][0]["upload_url"], content=HTML).status_code == 200
+ ready = _file_done(client, task, 0)
assert ready["status"] == "waiting_upload"
assert [file["upload_status"] for file in ready["files"]] == ["ready", "pending"]
assert [link["client_file_id"] for link in ready["uploads"]] == ["f2"]
- assert _job_count(app) == 0
+ assert _job_count(app) == 1
+ assert b"Preserved content" in _archive(client, ready)["markdown.md"]
_upload(client, ready, inputs)
result = _terminal(client, task)
- assert result["status"] == "completed"
- assert result["task_id"] == task["task_id"] and _job_count(app) == 1
- assert all("content" not in file for file in result["files"])
- assert client.get(f"/v1/parse/jobs/{task['task_id']}").json()["job_id"] == task["task_id"]
+ assert result["status"] == "completed" and _job_count(app) == 2
+ assert result["task_id"] == task["task_id"]
+ assert all("content" not in file and "output_files" not in file for file in result["files"])
+ assert client.get(f"/v1/parse/jobs/{task['task_id']}").status_code == 404
+ assert b"Second content" in _archive(client, result, 1)["markdown.md"]
members = _archive(client, result)
- assert b"Preserved content" in members["0001/markdown.md"]
- assert b"Second content" in members["0002/markdown.md"]
- manifest = json.loads(members["manifest.json"])
- assert manifest["status"] == "completed"
- assert [item["client_file_id"] for item in manifest["files"]] == ["f1", "f2"]
- assert [item["directory"] for item in manifest["files"]] == ["0001/", "0002/"]
- assert "task_id" not in manifest
- assert all("file_id" not in item and "output_files" not in item for item in manifest["files"])
- assert json.loads(members["0001/middle_json.json"])["schema"] == "docvortex.middle"
+ assert "manifest.json" not in members and "model_output.json" not in members
+ assert json.loads(members["middle_json.json"])["schema"] == "docvortex.middle"
assert client.get(f"/v1/tasks/{task['task_id']}/result").status_code == 404
assert client.post("/v1/file_parse").status_code == 404
assert client.post("/tasks").status_code == 404
assert client.get(f"/v1/files/{result['files'][0]['file_id']}/content").status_code == 403
[email protected]("hashes", [False, True])
-def test_single_multipart_is_asynchronous_and_checks_hash(service: tuple[TestClient, FastAPI], hashes: bool) -> None:
- """单文件直传保留便利性,实际发送的字节必须经过 hash 检查。"""
+def test_direct_and_form_submissions_are_rejected(service: tuple[TestClient, FastAPI]) -> None:
+ """无论单文件还是批量,创建请求都不能携带表单或文件主体。"""
client, app = service
- form: dict[str, Any] = {"tier": "flash"}
- if hashes:
- form["manifest"] = json.dumps(
- [
- {
- "client_file_id": "f1",
- "filename": "logical.html",
- "bytes": len(HTML),
- "sha256sum": hashlib.sha256(HTML).hexdigest(),
- }
- ]
- )
- response = client.post("/v1/tasks", data=form, files={"files": ("source.html", HTML)})
- assert response.status_code == 202, response.text
- result = _terminal(client, response.json())
- assert result["status"] == "completed"
- assert result["files"][0]["filename"] == ("logical.html" if hashes else "source.html")
- assert b"Shared tasks" in _archive(client, result)["markdown.md"]
- before = _job_count(app)
- invalid = client.post(
- "/v1/tasks",
- data={
- "manifest": json.dumps(
- [
- {
- "client_file_id": "f1",
- "filename": "source.html",
- "bytes": len(HTML),
- "sha256sum": hashlib.sha256(HTML).hexdigest(),
- }
- ]
- )
- },
- files={"files": ("source.html", HTML.replace(b"Shared", b"Broken"))},
- )
- assert invalid.status_code == 400 and invalid.json()["error"]["code"] == "file_hash_mismatch"
- assert _job_count(app) == before
+ for response in (
+ client.post("/v1/tasks", data={"tier": "flash"}),
+ client.post("/v1/tasks", files={"files": ("a.html", HTML)}),
+ client.post("/v1/tasks", content=HTML, headers={"content-type": "application/octet-stream"}),
+ ):
+ assert response.status_code == 415
+ assert _job_count(app) == 0
class _UnreadableBody(httpx.SyncByteStream):
@@ -288,7 +260,7 @@ def test_mixed_cache_hit_survives_source_deletion(service: tuple[TestClient, Fas
cached = _submit(client, inputs)
assert cached["uploads"] == [] and cached["status"] == "queued"
assert _terminal(client, cached)["status"] == "completed"
- assert _job_count(app) == 3
+ assert _job_count(app) == 5
def test_no_hash_still_deduplicates_source_storage(service: tuple[TestClient, FastAPI]) -> None:
@@ -302,31 +274,25 @@ def test_no_hash_still_deduplicates_source_storage(service: tuple[TestClient, Fa
_upload(client, second, [("second.html", HTML)])
assert _terminal(client, second)["status"] == "completed"
records = app.state.task_store._records
- assert records[first["task_id"]].uploads[0].path == records[second["task_id"]].uploads[0].path
+ assert records[first["task_id"]].files[0].upload.path == records[second["task_id"]].files[0].upload.path
def test_waiting_upload_retains_deleted_source_views(service: tuple[TestClient, FastAPI]) -> None:
- """等待其他文件期间删除源视图,不影响任务已经取得的字节引用。"""
+ """删除已解析源视图不影响已生成结果,也不阻止其他文件继续上传。"""
client, app = service
inputs = [("a.html", HTML), ("b.html", SECOND)]
task = _submit(client, inputs, hashes=False)
assert client.put(task["uploads"][0]["upload_url"], content=HTML).status_code == 200
- record = app.state.task_store._records[task["task_id"]]
- if hasattr(app.state, "file_store"):
- file_id = record.uploads[0].file_id
- assert app.state.file_store.get_file(file_id).expires_at is None
- assert client.delete(f"/v1/files/{file_id}").status_code == 200
- else:
- app.state.source_store.delete_file(record.backend._owned_files[0])
- assert record.uploads[0].path.is_file()
+ ready = _file_done(client, task, 0)
+ assert client.delete(f"/v1/files/{ready['files'][0]['file_id']}").status_code == 200
assert client.put(task["uploads"][1]["upload_url"], content=SECOND).status_code == 200
result = _terminal(client, task)
assert result["status"] == "completed", result
- assert b"Preserved content" in _archive(client, result)["0001/markdown.md"]
+ assert b"Preserved content" in _archive(client, result)["markdown.md"]
def test_failed_upload_can_retry_without_reuploading_ready_file(service: tuple[TestClient, FastAPI]) -> None:
- """一个文件校验失败只影响该项,其他成功文件保持 ready 且不提前创建 Job。"""
+ """校验失败可在期限内重传,不影响已经执行的其他文件。"""
client, app = service
inputs = [("a.html", HTML), ("b.html", SECOND)]
task = _submit(client, inputs)
@@ -335,16 +301,16 @@ def test_failed_upload_can_retry_without_reuploading_ready_file(service: tuple[T
assert failed.status_code == 400 and failed.json()["error"]["code"] == "file_hash_mismatch"
mismatch = client.put(task["uploads"][1]["upload_url"], content=SECOND + b"x")
assert mismatch.status_code == 400 and mismatch.json()["error"]["code"] == "upload_size_mismatch"
- pending = client.get(task["status_url"]).json()
- assert pending["status"] == "waiting_upload" and _job_count(app) == 0
+ pending = _file_done(client, task, 0)
+ assert pending["status"] == "waiting_upload" and _job_count(app) == 1
assert [file["upload_status"] for file in pending["files"]] == ["ready", "pending"]
assert list(app.state.task_store._records[task["task_id"]].directory.iterdir()) == []
_upload(client, pending, inputs)
- assert _terminal(client, task)["status"] == "completed" and _job_count(app) == 1
+ assert _terminal(client, task)["status"] == "completed" and _job_count(app) == 2
def test_concurrent_last_uploads_and_duplicate_put_submit_once(service: tuple[TestClient, FastAPI]) -> None:
- """并发上传与重复 PUT 共用提交门闩,批量文件只产生一个 Job。"""
+ """并发上传与重复 PUT 共用提交门闩,每个文件只产生一个 Job。"""
client, app = service
task = _submit(client, [("a.html", HTML), ("b.html", SECOND)])
@@ -360,30 +326,43 @@ def test_concurrent_last_uploads_and_duplicate_put_submit_once(service: tuple[Te
responses = client.portal.call(upload_all)
assert all(response.status_code == 200 for response in responses)
assert _terminal(client, task)["status"] == "completed"
- assert _job_count(app) == 1
+ assert _job_count(app) == 2
if hasattr(app.state, "worker_pool"):
assert sum(worker.active_jobs for worker in app.state.worker_pool.workers) == 0
-def test_cancel_and_expire_waiting_upload_release_inputs(service: tuple[TestClient, FastAPI]) -> None:
- """取消和过期不需要 worker,准备阶段保存的文件视图及引用都被释放。"""
[email protected]("expired", [False, True])
+def test_cancel_and_expire_waiting_upload_release_inputs(service: tuple[TestClient, FastAPI], expired: bool) -> None:
+ """取消或上传过期只终结未完成文件,已生成结果继续可下载。"""
client, app = service
- for expired in (False, True):
- task = _submit(client, [("a.html", HTML), ("b.html", SECOND)])
- assert client.put(task["uploads"][0]["upload_url"], content=HTML).status_code == 200
- record = app.state.task_store._records[task["task_id"]]
- if expired:
- record.expires_at = int(time.time()) - 1
- response = client.get(task["status_url"])
- assert response.json()["error"]["code"] == "upload_expired"
- else:
- response = client.delete(task["status_url"])
- assert response.status_code == 200
- assert response.json()["status"] == ("failed" if expired else "canceled")
- assert response.json()["uploads"] == [] and _job_count(app) == 0
- assert not record.directory.exists()
- assert record.backend._owned_files == []
- assert client.put(task["uploads"][1]["upload_url"], content=SECOND).status_code == 409
+ task = _submit(client, [("a.html", HTML), ("b.html", SECOND)])
+ assert client.put(task["uploads"][0]["upload_url"], content=HTML).status_code == 200
+ ready = _file_done(client, task, 0)
+ record = app.state.task_store._records[task["task_id"]]
+ if expired:
+ record.expires_at = int(time.time()) - 1
+ response = client.get(task["status_url"])
+ assert response.json()["files"][1]["error"]["code"] == "upload_expired"
+ assert response.json()["files"][1]["upload_status"] == "expired"
+ else:
+ response = client.delete(task["status_url"])
+ assert response.status_code == 200
+ assert response.json()["status"] == ("partial" if expired else "canceled")
+ assert response.json()["uploads"] == [] and _job_count(app) == 1
+ assert response.json()["files"][0]["result_url"] == ready["files"][0]["result_url"]
+ assert b"Preserved content" in _archive(client, response.json())["markdown.md"]
+ rejected = client.put(task["uploads"][1]["upload_url"], content=SECOND)
+ assert rejected.status_code == (410 if expired else 409)
+ if expired:
+ assert client.put(task["uploads"][0]["upload_url"], content=HTML).status_code == 410
+
+ async def wait_cleanup() -> None:
+ """等待父任务持有的清理句柄,避免按定时猜测引用是否已释放。"""
+ await record.operation
+
+ client.portal.call(wait_cleanup)
+ assert not record.directory.exists()
+ assert all(file.backend._owned_files == [] for file in record.files)
def test_cancel_running_task_releases_execution_slot(
@@ -405,7 +384,7 @@ def test_cancel_running_task_releases_execution_slot(
response = client.delete(task["status_url"])
assert response.status_code == 200, response.text
assert response.json()["status"] == "canceled"
- assert client.get(task["status_url"]).json()["result_url"] is None
+ assert client.get(task["status_url"]).json()["files"][0]["result_url"] is None
deadline = time.monotonic() + 5
operation = app.state.task_store._records[task["task_id"]].operation
while operation is not None and not operation.done():
@@ -418,65 +397,73 @@ def test_cancel_running_task_releases_execution_slot(
def test_status_never_reads_or_rebuilds_zip(service: tuple[TestClient, FastAPI], monkeypatch: pytest.MonkeyPatch) -> None:
- """批量 ZIP 在后台只构建一次,状态与流式下载均不调用整包读取方法。"""
+ """产物按输入各构建一次,多次状态查询和下载不读取整包或重新渲染。"""
+ from mineru.parser import task_outputs
+
client, _ = service
- combine = task_api._combine_archives
+ build = task_outputs.build_task_output
calls = 0
- def counted(*args: Any, **kwargs: Any) -> str:
- """统计实际后台打包次数,确认多次查询及下载不重新构建。"""
+ def counted(*args: Any, **kwargs: Any) -> Path:
+ """统计逐文件产物构建,避免轮询触发重复导出。"""
nonlocal calls
calls += 1
- return combine(*args, **kwargs)
+ return build(*args, **kwargs)
- monkeypatch.setattr(task_api, "_combine_archives", counted)
+ monkeypatch.setattr(task_outputs, "build_task_output", counted)
inputs = [("a.html", HTML), ("b.html", SECOND)]
task = _submit(client, inputs)
_upload(client, task, inputs)
result = _terminal(client, task)
- assert result["status"] == "completed" and calls == 1
+ assert result["status"] == "completed" and calls == 2
def forbid_read(*args: Any, **kwargs: Any) -> bytes:
- """完成后的状态与下载必须使用元数据或文件流,禁止 read_blob 整包读取。"""
+ """状态与流式下载禁止把完整结果读入内存。"""
raise AssertionError("Result body was read into memory")
monkeypatch.setattr(api_server.FileStore, "read_blob", forbid_read)
monkeypatch.setattr(api_server.FileStore, "read_file_data", forbid_read)
for _ in range(3):
- assert client.get(task["status_url"]).json()["result_url"] == result["result_url"]
- assert "manifest.json" in _archive(client, result)
- assert calls == 1
+ assert client.get(task["status_url"]).json()["files"] == result["files"]
+ assert "markdown.md" in _archive(client, result)
+ assert "markdown.md" in _archive(client, result, 1)
+ assert calls == 2
def test_partial_and_packaging_failure_have_honest_results(
service: tuple[TestClient, FastAPI], monkeypatch: pytest.MonkeyPatch
) -> None:
- """部分解析成功保留错误,打包失败不能发布 completed 或虚假的下载链接。"""
+ """解析或打包失败都按文件报告,不发布不可用链接,其他文件继续。"""
+ from mineru.parser import task_outputs
+
client, _ = service
inputs = [("same.html", HTML), ("broken.pdf", b"not a pdf")]
task = _submit(client, inputs)
_upload(client, task, inputs)
result = _terminal(client, task)
assert result["status"] == "partial" and result["files"][1]["error"]
- members = _archive(client, result)
- assert json.loads(members["manifest.json"])["status"] == "partial"
- assert not any(name.startswith("0002/") for name in members)
+ assert result["files"][1]["result_url"] is None
+ assert "markdown.md" in _archive(client, result)
+ original = task_outputs.build_task_output
- def fail_packaging(*args: Any, **kwargs: Any) -> str:
- """模拟 ZIP 落盘失败,执行状态必须反映产物不可用。"""
- raise OSError("simulated full disk")
+ def fail_packaging(result: Any, formats: Any, directory: Path) -> Path:
+ """仅让第二个输入导出失败,验证文件级隔离及诚实的成功状态。"""
+ if "Second content" in result.markdown():
+ raise OSError("simulated full disk")
+ return original(result, formats, directory)
- monkeypatch.setattr(task_api, "_combine_archives", fail_packaging)
+ monkeypatch.setattr(task_outputs, "build_task_output", fail_packaging)
good = [("a.html", HTML), ("b.html", SECOND)]
task = _submit(client, good)
_upload(client, task, good)
failed = _terminal(client, task)
- assert failed["status"] == "failed" and failed["result_url"] is None
- assert failed["error"]["code"] == "result_packaging_failed"
+ assert failed["status"] == "partial" and failed["files"][1]["result_url"] is None
+ assert failed["files"][1]["error"]["code"] == "result_packaging_failed"
+ assert "markdown.md" in _archive(client, failed)
def test_input_validation_and_openapi(service: tuple[TestClient, FastAPI]) -> None:
- """新协议只接受表单和单文件直传,OpenAPI 不再宣传旧入口及大小限制。"""
+ """请求与 OpenAPI 都使用严格 JSON 数组,旧格式与额外字段在接单前拒绝。"""
client, app = service
valid = {"client_file_id": "f1", "filename": "a.html", "bytes": len(HTML)}
for manifest in (
@@ -486,31 +473,25 @@ def test_input_validation_and_openapi(service: tuple[TestClient, FastAPI]) -> No
[{**valid, "bytes": 0}],
[{**valid, "sha256sum": "invalid"}],
[{**valid, "page_range": "invalid"}],
+ json.dumps([valid]),
):
- response = client.post("/v1/tasks", data={"manifest": json.dumps(manifest)})
- assert response.status_code == 400, response.text
- for response in (
- client.post("/v1/tasks?tier=flash", data={"manifest": json.dumps([valid])}),
- client.post("/v1/tasks", files=[("files", ("a.html", HTML)), ("files", ("b.html", SECOND))]),
- client.post(
- "/v1/tasks",
- data={"manifest": json.dumps([valid, {**valid, "client_file_id": "f2"}])},
- files={"files": ("a.html", HTML)},
- ),
- client.post("/v1/tasks", files={"files": ("a.html", b"")}),
- client.post("/v1/tasks", data={"manifest": json.dumps([valid]), "wait_timeout": "300"}),
- ):
- assert response.status_code == 400, response.text
- assert client.post("/v1/tasks", json={"files": []}).status_code == 415
- assert client.post("/v1/tasks", content=HTML, headers={"content-type": "application/octet-stream"}).status_code == 415
+ assert client.post("/v1/tasks", json={"manifest": manifest}).status_code == 400
+ for formats in ([], "default", ["markdown"], ["zip"], ["pdf"], [None]):
+ assert client.post("/v1/tasks", json={"manifest": [valid], "output_formats": formats}).status_code == 400
+ assert client.post("/v1/tasks?tier=flash", json={"manifest": [valid]}).status_code == 400
+ assert client.post("/v1/tasks", json={"manifest": [valid], "wait_timeout": 300}).status_code == 400
+ assert client.post("/v1/tasks", json={"files": []}).status_code == 400
+ assert client.post("/v1/tasks", content=b"{", headers={"content-type": "application/json"}).status_code == 400
assert _job_count(app) == 0
spec = client.get("/openapi.json").json()
- assert "/v1/file_parse" not in spec["paths"]
- assert "/v1/tasks/{task_id}/result" not in spec["paths"]
+ assert "/v1/file_parse" not in spec["paths"] and "/v1/tasks/{task_id}/result" not in spec["paths"]
creation = spec["paths"]["/v1/tasks"]["post"]
assert not creation.get("parameters")
- assert set(creation["requestBody"]["content"]) == {"application/x-www-form-urlencoded", "multipart/form-data"}
- assert "209715200" not in json.dumps(creation)
+ assert set(creation["requestBody"]["content"]) == {"application/json"}
+ assert creation["requestBody"]["content"]["application/json"]["schema"]["properties"]["manifest"]["type"] == "array"
+ assert "result_url" not in spec["components"]["schemas"]["TaskStatusResponse"]["properties"]
+ assert "result_url" in spec["components"]["schemas"]["TaskFileStatus"]["properties"]
+ assert "output_files" not in spec["components"]["schemas"]["TaskFileStatus"]["properties"]
limits = client.get("/v1/usage").json()["limits"]
assert limits["max_file_size_bytes"] is None and limits["max_pages_per_file"] is None
assert limits["max_files_per_job"] == 100
@@ -535,7 +516,7 @@ def test_url_inputs_download_in_worker_and_report_actual_metadata(
item = _url_manifest(**metadata)
if hasattr(app.state, "worker_pool"):
app.state.worker_pool.workers[0].features["sources"] = ["file_id"]
- response = client.post("/v1/tasks", data={"manifest": json.dumps([item])})
+ response = client.post("/v1/tasks", json={"manifest": [item]})
assert response.status_code == 202, response.text
task = response.json()
assert task["status"] == "queued" and task["uploads"] == []
@@ -567,10 +548,10 @@ def test_url_manifest_validation(service: tuple[TestClient, FastAPI], url_downlo
*[_url_manifest(bytes=value) for value in (0, -1, True, "10", 10.5)],
]
for item in invalid:
- response = client.post("/v1/tasks", data={"manifest": json.dumps([item])})
+ response = client.post("/v1/tasks", json={"manifest": [item]})
assert response.status_code == 400, response.text
- response = client.post("/v1/tasks", data={"manifest": json.dumps([_url_manifest()])}, files={"files": ("a.html", HTML)})
- assert response.status_code == 400
+ response = client.post("/v1/tasks", files={"files": ("a.html", HTML)})
+ assert response.status_code == 415
assert _job_count(app) == 0 and url_downloads == []
schema = client.get("/openapi.json").json()
assert "not_required" in schema["components"]["schemas"]["TaskFileStatus"]["properties"]["upload_status"]["enum"]
@@ -579,37 +560,29 @@ def test_url_manifest_validation(service: tuple[TestClient, FastAPI], url_downlo
def test_mixed_url_upload_partial_and_no_early_reservation(
service: tuple[TestClient, FastAPI], url_downloads: list[httpx.Request]
) -> None:
- """混合批次仅等待本地上传,URL 逐项失败不丢失同名成功项或目录顺序。"""
+ """URL 文件不等待客户端上传,错误和完成结果都按清单顺序独立返回。"""
client, app = service
manifest = [
_url_manifest(filename="same.html"),
{"client_file_id": "local", "filename": "same.html", "bytes": len(SECOND)},
_url_manifest(client_file_id="bad", url="https://source.example/missing"),
]
- response = client.post("/v1/tasks", data={"manifest": json.dumps(manifest)})
+ response = client.post("/v1/tasks", json={"manifest": manifest})
assert response.status_code == 202, response.text
task = response.json()
- assert task["status"] == "waiting_upload"
+ assert task["status"] == "queued"
assert [link["client_file_id"] for link in task["uploads"]] == ["local"]
- assert [file["upload_status"] for file in task["files"]] == ["not_required", "pending", "not_required"]
- assert _job_count(app) == 0 and url_downloads == []
- if hasattr(app.state, "worker_pool"):
- assert all(worker.active_jobs == 0 for worker in app.state.worker_pool.workers)
+ ready = _file_done(client, task, 0)
+ assert b"Preserved content" in _archive(client, ready)["markdown.md"]
+ assert ready["files"][1]["status"] == "waiting_upload"
assert client.put(task["uploads"][0]["upload_url"], content=SECOND).status_code == 200
result = _terminal(client, task)
- assert result["status"] == "partial"
- assert result["progress"] == {"completed": 2, "failed": 1, "total": 3}
+ assert result["status"] == "partial" and result["progress"] == {"completed": 2, "failed": 1, "total": 3}
assert result["files"][0]["bytes"] == len(HTML)
- assert result["files"][2]["error"] and result["files"][2]["bytes"] is None
- members = _archive(client, result)
- assert b"Preserved content" in members["0001/markdown.md"]
- assert b"Second content" in members["0002/markdown.md"]
- assert not any(name.startswith("0003/") for name in members)
- archived_inputs = json.loads(members["manifest.json"])["files"]
- assert [item["client_file_id"] for item in archived_inputs] == ["remote", "local", "bad"]
- assert archived_inputs[0]["bytes"] == len(HTML)
- assert archived_inputs[0]["sha256sum"] == hashlib.sha256(HTML).hexdigest()
- assert all("url" not in item for item in archived_inputs)
+ assert result["files"][2]["error"] and result["files"][2]["result_url"] is None
+ assert b"Second content" in _archive(client, result, 1)["markdown.md"]
+ assert [item["client_file_id"] for item in result["files"]] == ["remote", "local", "bad"]
+ assert _job_count(app) == 3
@pytest.mark.parametrize(
@@ -626,10 +599,10 @@ def test_url_download_failures_are_per_file(
) -> None:
"""下载及完整性错误进入文件错误;全失败不生成结果链接或实际元数据。"""
client, _ = service
- response = client.post("/v1/tasks", data={"manifest": json.dumps([_url_manifest(**metadata)])})
+ response = client.post("/v1/tasks", json={"manifest": [_url_manifest(**metadata)]})
assert response.status_code == 202
result = _terminal(client, response.json())
- assert result["status"] == "failed" and result["result_url"] is None
+ assert result["status"] == "failed" and result["files"][0]["result_url"] is None
assert result["files"][0]["status"] == "failed" and result["files"][0]["error"]["code"] == code
assert result["files"][0]["bytes"] == metadata.get("bytes")
assert len(url_downloads) == 1
@@ -643,9 +616,7 @@ def test_url_hash_does_not_skip_download(service: tuple[TestClient, FastAPI], ur
_upload(client, cached, inputs)
assert _terminal(client, cached)["status"] == "completed"
for _ in range(2):
- response = client.post(
- "/v1/tasks", data={"manifest": json.dumps([_url_manifest(sha256sum=hashlib.sha256(HTML).hexdigest())])}
- )
+ response = client.post("/v1/tasks", json={"manifest": [_url_manifest(sha256sum=hashlib.sha256(HTML).hexdigest())]})
assert response.status_code == 202
assert _terminal(client, response.json())["status"] == "completed"
assert len(url_downloads) == 2
@@ -657,7 +628,7 @@ def test_url_download_obeys_worker_policy_and_limit(
"""HTTP 开关和 URL 下载预算继续由真正执行下载的服务控制。"""
client, app = service
item = _url_manifest(url="http://source.example/opaque")
- response = client.post("/v1/tasks", data={"manifest": json.dumps([item])})
+ response = client.post("/v1/tasks", json={"manifest": [item]})
if hasattr(app.state, "worker_pool"):
assert response.status_code == 202
assert _terminal(client, response.json())["status"] == "failed"
@@ -668,14 +639,14 @@ def test_url_download_obeys_worker_policy_and_limit(
worker.state.allow_http_source = True
worker.state.max_url_bytes = len(HTML) - 1
worker.state.url_timeout = 7
- response = client.post("/v1/tasks", data={"manifest": json.dumps([item])})
+ response = client.post("/v1/tasks", json={"manifest": [item]})
result = _terminal(client, response.json())
assert result["status"] == "failed"
assert "max_url_bytes" in result["files"][0]["error"]["message"]
assert url_downloads[0].extensions["timeout"]["read"] == 7
for worker in _execution_apps(app):
worker.state.max_url_bytes = len(HTML)
- response = client.post("/v1/tasks", data={"manifest": json.dumps([item])})
+ response = client.post("/v1/tasks", json={"manifest": [item]})
assert _terminal(client, response.json())["status"] == "completed"
@@ -693,7 +664,7 @@ def test_url_html_preserves_source_context(
return await original(*args, **kwargs)
monkeypatch.setattr(api_server, "parse_async", inspect_context)
- response = client.post("/v1/tasks", data={"manifest": json.dumps([_url_manifest()])})
+ response = client.post("/v1/tasks", json={"manifest": [_url_manifest()]})
assert _terminal(client, response.json())["status"] == "completed"
assert len(contexts) == 1 and len(url_downloads) == 1
assert contexts[0].source_uri == _url_manifest()["url"]
@@ -708,8 +679,8 @@ def test_url_logical_filename_drives_flash_fallback(
client, _ = service
response = client.post(
"/v1/tasks",
- data={
- "manifest": json.dumps([_url_manifest(url="https://source.example/document.pdf")]),
+ json={
+ "manifest": [_url_manifest(url="https://source.example/document.pdf")],
"tier": "standard",
},
)
@@ -753,7 +724,7 @@ def test_cancel_url_download_closes_stream_and_releases_worker(
return httpx.AsyncClient(transport=httpx.MockTransport(respond), **kwargs)
monkeypatch.setattr(api_server, "httpx", SimpleNamespace(AsyncClient=download_client))
- response = client.post("/v1/tasks", data={"manifest": json.dumps([_url_manifest()])})
+ response = client.post("/v1/tasks", json={"manifest": [_url_manifest()]})
assert response.status_code == 202
task = response.json()
assert started.wait(5)
@@ -771,7 +742,7 @@ def test_cancel_url_download_closes_stream_and_releases_worker(
assert time.monotonic() < deadline, "Canceled URL task retained its worker reservation"
time.sleep(0.01)
final = client.get(task["status_url"]).json()
- assert final["status"] == "canceled" and final["result_url"] is None
+ assert final["status"] == "canceled" and final["files"][0]["result_url"] is None
assert final["files"][0]["bytes"] is None
@@ -788,7 +759,7 @@ def test_router_private_hash_cache_and_task_scope(tmp_path: Path) -> None:
_upload(client, task, [("a.html", HTML)], headers=owner)
result = _terminal(client, task, headers=owner)
assert client.get(task["status_url"], headers=stranger).status_code == 404
- assert client.get(result["result_url"], headers=stranger).status_code == 404
+ assert client.get(result["files"][0]["result_url"], headers=stranger).status_code == 404
other = _submit(client, [("a.html", HTML)], headers=stranger)
assert len(other["uploads"]) == 1
assert client.delete(other["status_url"], headers=stranger).status_code == 200
@@ -803,11 +774,202 @@ def test_task_links_respect_proxy_root(tmp_path: Path, root: str) -> None:
app = api_server.create_app(upload_dir=str(tmp_path), tier="flash", api_key="secret")
with TestClient(app, root_path=root, headers={"Authorization": "Bearer secret"}) as client:
manifest = [{"client_file_id": "f1", "filename": "a.html", "bytes": len(HTML)}]
- response = client.post(root + "/v1/tasks", data={"manifest": json.dumps(manifest), "tier": "flash"})
+ response = client.post(root + "/v1/tasks", json={"manifest": manifest, "tier": "flash"})
assert response.status_code == 202
task = response.json()
assert task["status_url"].startswith("http://testserver" + root + "/v1/tasks/")
_upload(client, task, [("a.html", HTML)])
result = _terminal(client, task)
- assert result["result_url"].startswith("http://testserver" + root + "/v1/files/")
+ assert result["files"][0]["result_url"].startswith("http://testserver" + root + "/v1/files/")
assert "markdown.md" in _archive(client, result)
+
+
[email protected]("interrupted", [False, True])
+def test_inflight_upload_may_finish_after_deadline(service: tuple[TestClient, FastAPI], interrupted: bool) -> None:
+ """截止前受理的流可以传完;若跨截止时间断连,该文件失败且不能续传。"""
+ from starlette.requests import ClientDisconnect
+
+ client, app = service
+ task = _submit(client, [("a.html", HTML), ("b.html", SECOND)], hashes=False)
+ record = app.state.task_store._records[task["task_id"]]
+ expires_at = task["uploads"][0]["expires_at"]
+ assert 3598 <= expires_at - time.time() <= 3600
+ assert client.get(task["status_url"]).json()["uploads"][0]["expires_at"] == expires_at
+
+ async def cross_deadline() -> httpx.Response:
+ """让真实 ASGI 上传跨过时限,并在受理流中途并发查询和尝试新 PUT。"""
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") as transport:
+
+ async def body() -> AsyncIterator[bytes]:
+ """第一块已经被接收后模拟到期,仍在传输的文件不能被清理。"""
+ yield HTML[:10]
+ assert record.files[0].upload_active
+ record.expires_at = int(time.time()) - 1
+ state = (await transport.get(task["status_url"])).json()
+ assert state["files"][0]["status"] == "waiting_upload"
+ assert state["files"][1]["status"] == "failed"
+ assert state["uploads"] == []
+ rejected = await transport.put(task["uploads"][1]["upload_url"], content=SECOND)
+ assert rejected.status_code == 410
+ if interrupted:
+ raise ClientDisconnect
+ yield HTML[10:]
+
+ return await transport.put(task["uploads"][0]["upload_url"], content=body())
+
+ response = client.portal.call(cross_deadline)
+ result = _terminal(client, task)
+ if interrupted:
+ assert response.status_code == 400
+ assert result["status"] == "failed"
+ assert all(file["error"]["code"] == "upload_expired" for file in result["files"])
+ else:
+ assert response.status_code == 200
+ assert result["status"] == "partial"
+ assert b"Preserved content" in _archive(client, result)["markdown.md"]
+ assert client.put(task["uploads"][0]["upload_url"], content=HTML).status_code == 410
+
+
+def test_expired_upload_rejects_before_reading_body(service: tuple[TestClient, FastAPI]) -> None:
+ """链接截止后连重传主体也不读取,查询不能延长或重建上传窗口。"""
+ client, app = service
+ task = _submit(client, [("a.html", HTML)], hashes=False)
+ app.state.task_store._records[task["task_id"]].expires_at = int(time.time()) - 1
+ response = client.put(task["uploads"][0]["upload_url"], content=_UnreadableBody())
+ assert response.status_code == 410 and response.json()["error"]["code"] == "upload_expired"
+ for _ in range(2):
+ state = client.get(task["status_url"]).json()
+ assert state["status"] == "failed" and state["uploads"] == []
+ assert state["files"][0]["upload_status"] == "expired"
+ assert _job_count(app) == 0
+
+
+def test_completed_child_retention_starts_after_parent_finishes(service: tuple[TestClient, FastAPI]) -> None:
+ """子结果不能在父任务仍等待上传时过期,父任务完成后才开始统一保留期。"""
+ client, app = service
+ app.state.task_store.retention_seconds = 1
+ if hasattr(app.state, "registry"):
+ app.state.registry.retention_seconds = 1
+ for worker in _execution_apps(app):
+ worker.state.task_store.retention_seconds = 1
+ worker.state.job_store.retention_seconds = 1
+ worker.state.file_store.retention_seconds = 1
+ task = _submit(client, [("a.html", HTML), ("b.html", SECOND)], hashes=False)
+ assert client.put(task["uploads"][0]["upload_url"], content=HTML).status_code == 200
+ ready = _file_done(client, task, 0)
+ result_url = ready["files"][0]["result_url"]
+ time.sleep(1.05)
+ for worker in _execution_apps(app):
+ worker.state.job_store.collect_expired()
+ worker.state.file_store.collect_expired()
+ assert client.get(task["status_url"]).json()["files"][0]["status"] == "completed"
+ assert client.get(result_url).status_code == 200
+ assert client.put(task["uploads"][1]["upload_url"], content=SECOND).status_code == 200
+ assert _terminal(client, task)["status"] == "completed"
+ record = app.state.task_store._records[task["task_id"]]
+
+ async def finish_retention() -> None:
+ """等待统一保留起点,确保测试不依赖后台轮询间隔。"""
+ await record.operation
+
+ client.portal.call(finish_retention)
+ assert client.get(result_url).status_code == 200
+ time.sleep(1.05)
+ assert client.get(task["status_url"]).status_code == 404
+ assert client.get(result_url).status_code == 404
+
+
+def test_router_batch_uses_independent_workers_and_task_capabilities(tmp_path: Path) -> None:
+ """单个父任务的文件按负载分发,旧 worker 即使声明 zip 也不能接新 Tasks。"""
+ workers = {host: api_server.create_app(upload_dir=str(tmp_path / host), tier="flash") for host in ("worker-a", "worker-b")}
+ app = create_router(
+ RouterSettings(
+ upstream_urls=("http://worker-a", "http://worker-b"), local_gpus="none", worker_refresh_interval_seconds=0
+ ),
+ transport=_WorkerTransport(workers),
+ )
+ with TestClient(app) as client:
+ task = _submit(client, [("a.html", HTML), ("b.html", SECOND)])
+ _upload(client, task, [("a.html", HTML), ("b.html", SECOND)])
+ assert _terminal(client, task)["status"] == "completed"
+ assert {route.worker_id for route in app.state.registry.list("job")} == {
+ worker.worker_id for worker in app.state.worker_pool.workers
+ }
+ assert all(worker.active_jobs == 0 for worker in app.state.worker_pool.workers)
+ for worker in app.state.worker_pool.workers:
+ worker.features.pop("task_output_formats")
+ response = client.post(
+ "/v1/tasks", json={"manifest": [{"client_file_id": "f1", "filename": "a.html", "bytes": len(HTML)}]}
+ )
+ assert response.status_code == 503
+ assert all(worker.active_jobs == 0 for worker in app.state.worker_pool.workers)
+
+
+def test_worker_upload_renews_result_lease_after_long_transfer(tmp_path: Path) -> None:
+ """Router 转传超过内部租约长度时,上传完成会保护刚生成的子结果。"""
+ app = api_server.create_app(upload_dir=str(tmp_path), tier="flash")
+ with TestClient(app) as client:
+ task = _submit(client, [("a.html", HTML)], hashes=False)
+ record = app.state.task_store._records[task["task_id"]]
+
+ async def upload_long_stream() -> None:
+ """在流中模拟内部租约已到期,不改变独立的一小时上传窗口。"""
+
+ async def content() -> AsyncIterator[bytes]:
+ """接收第一块后推进租约边界,余下数据仍正常上传。"""
+ yield HTML[:10]
+ record.lease_expires_at = time.time() - 1
+ yield HTML[10:]
+
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") as transport:
+ response = await transport.put(
+ task["uploads"][0]["upload_url"], content=content(), headers={"x-mineru-task-lease-seconds": "120"}
+ )
+ assert response.status_code == 200
+ assert record.lease_expires_at > time.time() + 110
+
+ client.portal.call(upload_long_stream)
+ result = _terminal(client, task)
+ assert result["status"] == "completed" and record.retention_epoch is None
+ assert client.get(result["files"][0]["result_url"]).status_code == 200
+ assert client.get(task["status_url"], headers={"x-mineru-task-lease-seconds": "0"}).status_code == 200
+
+
+def test_router_ends_local_result_lease_even_if_worker_rejects_release(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """保留期结束后 worker 拒绝释放请求也不能永久保留过期的本地路由。"""
+ from mineru.kit.router.tasks import maintain_task_result_leases
+
+ worker = api_server.create_app(upload_dir=str(tmp_path), tier="flash")
+ transport = _WorkerTransport({"worker-a": worker})
+ app = create_router(
+ RouterSettings(upstream_urls=("http://worker-a",), local_gpus="none", worker_refresh_interval_seconds=0),
+ transport=transport,
+ )
+ with TestClient(app) as client:
+ task = _submit(client, [("a.html", HTML)])
+ _upload(client, task, [("a.html", HTML)])
+ result = _terminal(client, task)
+ record = app.state.task_store._records[task["task_id"]]
+
+ async def prepare() -> None:
+ """等待父任务清理,并把其子路由保留期限推进到过去。"""
+ await record.operation
+ for route in app.state.registry.list("job"):
+ route.metadata["task_result_retain_until"] = time.time() - 1
+
+ client.portal.call(prepare)
+ original = transport.handle_async_request
+
+ async def reject_release(request: httpx.Request) -> httpx.Response:
+ """模拟 worker 的凭证轮换,结果租约释放返回明确的认证错误。"""
+ if request.headers.get("x-mineru-task-lease-seconds") == "0":
+ return httpx.Response(403, request=request)
+ return await original(request)
+
+ monkeypatch.setattr(transport, "handle_async_request", reject_release)
+ client.portal.call(maintain_task_result_leases, app.state.registry, app.state.worker_pool)
+ assert all(not route.metadata.get("task_result_held") for route in app.state.registry.list("job", include_expired=True))
+ assert all(
+ not route.metadata.get("task_result_held") for route in app.state.registry.list("file", include_expired=True)
+ )
+ assert result["files"][0]["result_url"]
diff --git a/tests/unittest/test_task_http.py b/tests/unittest/test_task_http.py
index 7cc5b90c..c3f9706a 100644
--- a/tests/unittest/test_task_http.py
+++ b/tests/unittest/test_task_http.py
@@ -114,7 +114,7 @@ def _client(service: _LiveService) -> httpx.Client:
def _submit(client: httpx.Client, files: list[tuple[str, bytes]], *, hashes: bool = True, **options: Any) -> dict[str, Any]:
- """以表单提交文件清单,hash 缺省时不放入任何替代标识。"""
+ """以 JSON 提交文件清单,hash 缺省时不放入任何替代标识。"""
manifest = [
{
"client_file_id": f"f{index + 1}",
@@ -124,7 +124,7 @@ def _submit(client: httpx.Client, files: list[tuple[str, bytes]], *, hashes: boo
}
for index, (name, data) in enumerate(files)
]
- response = client.post("/v1/tasks", data={"manifest": json.dumps(manifest), "tier": "flash", "ocr_mode": "txt", **options})
+ response = client.post("/v1/tasks", json={"manifest": manifest, "tier": "flash", "ocr_mode": "txt", **options})
assert response.status_code == 202, response.text
return response.json()
@@ -138,7 +138,7 @@ def _wait(client: httpx.Client, task: dict[str, Any], timeout: float = 60) -> di
payload = response.json()
if payload["status"] in TERMINAL:
return payload
- assert payload["result_url"] is None
+ assert all(file["result_url"] is None for file in payload["files"] if file["status"] != "completed")
time.sleep(0.02)
pytest.fail("Task did not complete over HTTP")
@@ -159,7 +159,7 @@ def _script_env(tmp_path: Path, base: str, **extra: str) -> dict[str, str]:
"MINERU_PYTHON": sys.executable,
"MINERU_TIER": "flash",
"OCR_MODE": "txt",
- "RESULT_FILE": str(tmp_path / "result.zip"),
+ "RESULT_DIR": str(tmp_path / "results"),
"MAX_POLLS": "100",
"POLL_INTERVAL": "0.02",
"REQUEST_TIMEOUT": "30",
@@ -176,19 +176,30 @@ def _run_script(env: dict[str, str], *paths: Path) -> subprocess.CompletedProces
)
[email protected]("mode,hashes,count", [("preflight", "1", 2), ("preflight", "0", 1), ("direct", "1", 1)])
-def test_documented_client_script(live_service: _LiveService, tmp_path: Path, mode: str, hashes: str, count: int) -> None:
- """同一脚本处理本地、Router、单文件直传和多文件逐项上传。"""
+ "formats,hashes,count",
+ [("default", "1", 2), ("default", "0", 1), ("html", "1", 1), ("docx", "1", 1), ("default,latex,html,docx", "1", 2)],
+)
+def test_documented_client_script(live_service: _LiveService, tmp_path: Path, formats: str, hashes: str, count: int) -> None:
+ """同一客户端以 JSON 创建任务,按文件保存 ZIP、HTML 或 DOCX。"""
paths: list[Path] = []
for index in range(count):
path = tmp_path / f"测试 文档 {index}.html"
path.write_text(f"<h1>中文内容 {index}</h1>", encoding="utf-8")
paths.append(path)
- result = _run_script(_script_env(tmp_path, live_service.url, UPLOAD_MODE=mode, SEND_HASH=hashes), *paths)
+ result = _run_script(_script_env(tmp_path, live_service.url, OUTPUT_FORMATS=formats, SEND_HASH=hashes), *paths)
assert result.returncode == 0, result.stdout + result.stderr
assert "task_id=" in result.stderr
- members = _members((tmp_path / "result.zip").read_bytes())
- assert "中文内容".encode() in members["0001/markdown.md" if count > 1 else "markdown.md"]
+ for index, path in enumerate(paths):
+ extension = formats if formats in {"html", "docx"} else "zip"
+ output = tmp_path / "results" / f"f{index + 1}" / (path.stem + "." + extension)
+ assert output.is_file()
+ if extension == "zip":
+ assert "中文内容".encode() in _members(output.read_bytes())["markdown.md"]
+ elif extension == "html":
+ assert "中文内容" in output.read_text()
+ else:
+ assert "word/document.xml" in _members(output.read_bytes())
def test_hash_preflight_sends_only_missing_file_bytes(live_service: _LiveService) -> None:
@@ -212,12 +223,10 @@ def test_hash_preflight_sends_only_missing_file_bytes(live_service: _LiveService
denied = client.post(
"/v1/tasks",
headers={"Authorization": "Bearer wrong"},
- data={
- "manifest": json.dumps(
- [
- {"client_file_id": "f1", "filename": "a.html", "bytes": len(HTML)},
- ]
- )
+ json={
+ "manifest": [
+ {"client_file_id": "f1", "filename": "a.html", "bytes": len(HTML)},
+ ]
},
)
assert denied.status_code == 401
@@ -248,15 +257,15 @@ def test_disconnect_then_resume_keeps_uploaded_files(live_service: _LiveService,
finally:
connection.close()
pending = client.get(task["status_url"]).json()
- assert pending["status"] == "waiting_upload"
+ assert pending["status"] in {"waiting_upload", "queued", "running"}
assert [item["upload_status"] for item in pending["files"]] == ["ready", "pending"]
result = _run_script(_script_env(tmp_path, live_service.url, TASK_ID=task["task_id"]), first_path, second_path)
assert result.returncode == 0, result.stdout + result.stderr
assert live_service.counts[urlsplit(task["uploads"][0]["upload_url"]).path] == len(HTML)
assert live_service.counts[target.path] == len(prefix) + len(second)
assert len(live_service.app.state.task_store._records) == 1
- members = _members((tmp_path / "result.zip").read_bytes())
- assert b"Resumed file" in members["0002/markdown.md"]
+ members = _members((tmp_path / "results/f2/b.zip").read_bytes())
+ assert b"Resumed file" in members["markdown.md"]
final = client.get(task["status_url"]).json()
assert final["task_id"] == task["task_id"] and final["status"] == "completed"
@@ -282,23 +291,17 @@ def test_cancel_response_does_not_wait_for_native_thread_cleanup(
canceled = client.delete(task["status_url"], timeout=2)
assert canceled.status_code == 200 and canceled.json()["status"] == "canceled"
assert not release.is_set()
- assert client.get(task["status_url"]).json()["result_url"] is None
+ assert client.get(task["status_url"]).json()["files"][0]["result_url"] is None
finally:
release.set()
[email protected]("upload_mode", ["preflight", "direct"])
-def test_upload_over_200_mib_is_accepted(
- live_service: _LiveService,
- tmp_path: Path,
- monkeypatch: pytest.MonkeyPatch,
- upload_mode: str,
-) -> None:
- """超过旧上限的完整文件经过真实 HTTP 和 worker 转发,校验后才进入解析。"""
+def test_upload_over_200_mib_is_accepted(live_service: _LiveService, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """超过旧上限的完整文件经过真实 HTTP 和 worker 转发,校验后才解析。"""
started = threading.Event()
async def pause_parser(path: str, **kwargs: Any) -> None:
- """只隔离耗时解析,真实源文件读取、完整上传和转发均保留。"""
+ """只隔离耗时解析,保留完整源文件接收、转发和字节校验。"""
assert Path(path).stat().st_size == 200 * 1024 * 1024 + 4096
started.set()
await asyncio.Event().wait()
@@ -311,32 +314,18 @@ def test_upload_over_200_mib_is_accepted(
output.seek(size - 1)
output.write(b"\n")
with _client(live_service) as client:
- if upload_mode == "direct":
- with source.open("rb") as stream:
- response = client.post("/v1/tasks", data={"tier": "flash"}, files={"files": (source.name, stream)})
- assert response.status_code == 202, response.text
- task = response.json()
- else:
- response = client.post(
- "/v1/tasks",
- data={
- "tier": "flash",
- "manifest": json.dumps(
- [
- {"client_file_id": "large", "filename": source.name, "bytes": size},
- ]
- ),
- },
- )
- assert response.status_code == 202, response.text
- task = response.json()
- with source.open("rb") as stream:
- uploaded = client.put(task["uploads"][0]["upload_url"], content=stream, headers={"Content-Length": str(size)})
- assert uploaded.status_code == 200, uploaded.text
- assert live_service.counts[urlsplit(task["uploads"][0]["upload_url"]).path] == size
+ response = client.post(
+ "/v1/tasks",
+ json={"tier": "flash", "manifest": [{"client_file_id": "large", "filename": source.name, "bytes": size}]},
+ )
+ assert response.status_code == 202, response.text
+ task = response.json()
+ with source.open("rb") as stream:
+ uploaded = client.put(task["uploads"][0]["upload_url"], content=stream, headers={"Content-Length": str(size)})
+ assert uploaded.status_code == 200, uploaded.text
+ assert live_service.counts[urlsplit(task["uploads"][0]["upload_url"]).path] == size
assert started.wait(60)
- status = client.get(task["status_url"]).json()
- assert status["files"][0]["upload_status"] == "ready"
+ assert client.get(task["status_url"]).json()["files"][0]["upload_status"] == "ready"
assert client.delete(task["status_url"]).json()["status"] == "canceled"
@@ -354,7 +343,7 @@ def test_large_page_count_pdf_is_not_rejected(live_service: _LiveService, page_c
assert client.put(task["uploads"][0]["upload_url"], content=data).status_code == 200
result = _wait(client, task, timeout=90)
assert result["status"] == "completed", result
- download = client.get(result["result_url"])
+ download = client.get(result["files"][0]["result_url"])
middle = json.loads(_members(download.content)["middle_json.json"])
assert len(middle["pages"]) == page_count
assert middle["pages"][-1]["page_idx"] == page_count - 1
@@ -372,7 +361,7 @@ def test_real_documents_match_jobs_outputs(live_service: _LiveService, document:
data, name, page_range = HTML, "source.html", ""
formats = ["markdown", "middle_json", "structured_content", "zip"]
with _client(live_service) as client:
- task = _submit(client, [(name, data)], page_range=page_range, output_formats=formats)
+ task = _submit(client, [(name, data)], page_range=page_range, output_formats=["default"])
assert client.put(task["uploads"][0]["upload_url"], content=data).status_code == 200
result = _wait(client, task)
assert result["status"] == "completed", result
@@ -396,10 +385,12 @@ def test_real_documents_match_jobs_outputs(live_service: _LiveService, document:
assert time.monotonic() < deadline
time.sleep(0.02)
assert baseline["status"] == "completed", baseline
- first = client.get(result["result_url"])
+ first = client.get(result["files"][0]["result_url"])
second = client.get(f"/v1/files/{baseline['files'][0]['output_files']['zip']['file_id']}/content")
assert first.status_code == second.status_code == 200
- assert _members(first.content) == _members(second.content)
+ assert {k: v for k, v in _members(first.content).items() if k != "images/"} == {
+ k: v for k, v in _members(second.content).items() if k != "model_output.json"
+ }
@pytest.mark.parametrize("document", ["html", "pdf"])
@@ -447,8 +438,8 @@ def test_url_task_over_http_downloads_chunked_source(live_service: _LiveService,
with _client(live_service) as client:
response = client.post(
"/v1/tasks",
- data={
- "manifest": json.dumps([item]),
+ json={
+ "manifest": [item],
"tier": "flash",
"ocr_mode": "txt",
"page_range": "1" if document == "pdf" else "",
@@ -461,7 +452,7 @@ def test_url_task_over_http_downloads_chunked_source(live_service: _LiveService,
assert result["status"] == "completed", result
assert result["files"][0]["bytes"] == len(data)
assert result["files"][0]["sha256sum"] == hashlib.sha256(data).hexdigest()
- members = _members(client.get(result["result_url"]).content)
+ members = _members(client.get(result["files"][0]["result_url"]).content)
assert live_service.counts == {}
assert len(requests) == 1 and requests[0].method == "GET"
assert requests[0].scope["query_string"] == b"signature=a%2Fb&part=1"
@@ -494,9 +485,11 @@ def test_url_task_over_http_downloads_chunked_source(live_service: _LiveService,
assert client.put(baseline["uploads"][0]["upload_url"], content=data).status_code == 200
baseline_result = _wait(client, baseline)
assert baseline_result["status"] == "completed"
- baseline_url = baseline_result["result_url"]
+ baseline_url = baseline_result["files"][0]["result_url"]
baseline_members = _members(client.get(baseline_url).content)
- assert members == baseline_members
+ assert {k: v for k, v in members.items() if k != "images/"} == {
+ k: v for k, v in baseline_members.items() if k not in {"model_output.json", "images/"}
+ }
if document == "pdf":
middle = json.loads(members["middle_json.json"])
assert len(middle["pages"]) == 1 and middle["pages"][0]["page_idx"] == 1
@@ -524,45 +517,63 @@ class _CloudState:
invalid_response: str | None = None
def payload(self, task_id: str) -> dict[str, Any]:
- """只从元数据生成响应,网关不读取对象存储中的结果字节。"""
+ """只从逐文件元数据生成状态与链接,完成文件不等待其他输入。"""
record = self.tasks[task_id]
- ready = record["ready"]
- status = (self.forced_status or "completed") if len(ready) == len(record["manifest"]) else "waiting_upload"
- files = [
- {
- **item,
- "name": item["filename"],
- "upload_status": "ready" if item["client_file_id"] in ready else "pending",
- "status": "completed" if status in {"completed", "partial"} else "queued",
- }
- for item in record["manifest"]
- ]
- result_url = None
- if status in {"completed", "partial"}:
- result_url = f"{self.storage_url}/download/{task_id}?signature={record['download_version']}"
- if self.api_download_redirect:
- result_url = f"{self.gateway_url}/redirect/{task_id}"
+ ready, expired = record["ready"], record["expired"]
+ files = []
+ for index, item in enumerate(record["manifest"]):
+ client_id = item["client_file_id"]
+ status = "completed" if client_id in ready else "waiting_upload"
+ if client_id in expired:
+ status = "failed"
+ if client_id in ready and self.forced_status in {"failed", "running"}:
+ status = self.forced_status
+ if self.forced_status == "partial" and index == len(record["manifest"]) - 1 and client_id in ready:
+ status = "failed"
+ result_url = None
+ if status == "completed":
+ result_url = f"{self.storage_url}/download/{task_id}/{client_id}?signature={record['download_version']}"
+ if self.api_download_redirect:
+ result_url = f"{self.gateway_url}/redirect/{task_id}/{client_id}"
+ files.append(
+ {
+ **item,
+ "name": item["filename"],
+ "upload_status": "ready" if client_id in ready else ("expired" if client_id in expired else "pending"),
+ "status": status,
+ "result_url": result_url,
+ }
+ )
+ states = [item["status"] for item in files]
+ if "running" in states:
+ status = "running"
+ elif "waiting_upload" in states:
+ status = "waiting_upload"
+ else:
+ status = (
+ "completed"
+ if all(value == "completed" for value in states)
+ else ("partial" if "completed" in states else "failed")
+ )
uploads = [
{
"client_file_id": item["client_file_id"],
"upload_method": "PUT",
- "upload_url": (
- f"{self.storage_url}/objects/{task_id}/{item['client_file_id']}?signature={record['upload_version']}"
- ),
+ "upload_url": f"{self.storage_url}/objects/{task_id}/{item['client_file_id']}?signature=0",
"upload_headers": {"Content-Type": "application/octet-stream", "X-Upload-Token": "storage-token"},
- "expires_at": int(time.time()) + 3600,
+ "expires_at": record["expires_at"],
}
for item in record["manifest"]
- if item["client_file_id"] not in ready
+ if item["client_file_id"] not in ready | expired
]
payload = {
"task_id": task_id,
"status": status,
"status_url": f"{self.gateway_url}/v1/tasks/{task_id}",
- "result_url": result_url,
"files": files,
"uploads": uploads,
"error": None,
+ "output_formats": record["output_formats"],
}
if self.invalid_response == "missing_id":
payload["task_id"] = None
@@ -585,20 +596,23 @@ def _cloud_apps(state: _CloudState) -> tuple[FastAPI, FastAPI]:
@gateway.post("/v1/tasks")
async def create_task(request: Request) -> Response:
- """只接收体积很小的表单元数据,用 hash 判断哪些文件需要独立上传。"""
+ """只接收体积很小的 JSON 元数据,用 hash 判断哪些文件需要独立上传。"""
assert not request.query_params
- assert request.headers["content-type"].startswith("application/x-www-form-urlencoded")
+ assert request.headers["content-type"].startswith("application/json")
body = await request.body()
state.gateway_body_sizes.append(len(body))
assert len(body) < 4096
- form = await request.form()
- manifest = json.loads(form["manifest"])
+ submitted = await request.json()
+ manifest = submitted["manifest"]
task_id = f"cloud_{len(state.tasks) + 1}"
state.tasks[task_id] = {
"manifest": manifest,
"ready": {item["client_file_id"] for item in manifest if item.get("sha256sum") in state.cache},
"upload_version": 0,
"download_version": 0,
+ "expired": set(),
+ "expires_at": int(time.time()) + 3600,
+ "output_formats": submitted["output_formats"],
}
return JSONResponse(state.payload(task_id), status_code=202)
@@ -607,11 +621,11 @@ def _cloud_apps(state: _CloudState) -> tuple[FastAPI, FastAPI]:
"""仅返回元数据和 OSS 下载链接,不回源读取或代理 ZIP 内容。"""
return JSONResponse(state.payload(task_id))
- @gateway.get("/redirect/{task_id}")
- async def redirect(task_id: str) -> Response:
+ @gateway.get("/redirect/{task_id}/{client_file_id}")
+ async def redirect(task_id: str, client_file_id: str) -> Response:
"""模拟同源下载地址重定向到同主机不同端口,检查客户端凭据隔离。"""
return RedirectResponse(
- f"{state.storage_url}/download/{task_id}?signature={state.tasks[task_id]['download_version']}",
+ f"{state.storage_url}/download/{task_id}/{client_file_id}?signature={state.tasks[task_id]['download_version']}",
status_code=302,
)
@@ -632,8 +646,8 @@ def _cloud_apps(state: _CloudState) -> tuple[FastAPI, FastAPI]:
if request.query_params.get("signature") != str(record["upload_version"]):
return Response(status_code=403)
if state.expired_upload and record["upload_version"] == 0:
- record["upload_version"] = 1
- return Response(status_code=403)
+ record["expired"].add(client_file_id)
+ return Response(status_code=410)
if state.transient_upload and state.upload_attempts[key] == 1:
return Response(status_code=503)
data = await request.body()
@@ -647,8 +661,8 @@ def _cloud_apps(state: _CloudState) -> tuple[FastAPI, FastAPI]:
return Response(status_code=503)
return Response(status_code=200)
- @storage.get("/download/{task_id}")
- async def download(task_id: str, request: Request) -> Response:
+ @storage.get("/download/{task_id}/{client_file_id}")
+ async def download(task_id: str, client_file_id: str, request: Request) -> Response:
"""结果字节仅由对象存储返回;过期地址通过再次查询原任务刷新。"""
record = state.tasks[task_id]
if request.query_params.get("signature") != str(record["download_version"]):
@@ -658,8 +672,7 @@ def _cloud_apps(state: _CloudState) -> tuple[FastAPI, FastAPI]:
return Response(status_code=403)
output = io.BytesIO()
with zipfile.ZipFile(output, "w") as archive:
- archive.writestr("result.md", "# OSS result\n")
- archive.writestr("manifest.json", json.dumps({"task_id": task_id, "status": state.forced_status or "completed"}))
+ archive.writestr("markdown.md", f"# OSS result {client_file_id}\n")
return Response(output.getvalue(), media_type="application/zip")
return gateway, storage
@@ -700,12 +713,10 @@ def test_same_client_works_with_saas_and_oss(cloud: _CloudState, tmp_path: Path,
assert not any(surface == "gateway" and method == "PUT" for surface, method, _, _ in cloud.requests)
assert not any(path.endswith("/result") for _, _, path, _ in cloud.requests)
assert all(auth is None for surface, _, _, auth in cloud.requests if surface == "storage")
- assert _members((tmp_path / "result.zip").read_bytes())["result.md"] == b"# OSS result\n"
+ assert _members((tmp_path / "results/f1/a.zip").read_bytes())["markdown.md"] == b"# OSS result f1\n"
- "failure", ["transient_upload", "lost_upload_response", "expired_upload", "expired_download", "api_download_redirect"]
-)
[email protected]("failure", ["transient_upload", "lost_upload_response", "expired_download", "api_download_redirect"])
def test_client_recovers_links_and_uncertain_uploads(cloud: _CloudState, tmp_path: Path, failure: str) -> None:
"""恢复原任务和刷新地址不创建新任务;跨源重定向不能转发 API Key。"""
setattr(cloud, failure, True)
@@ -714,9 +725,9 @@ def test_client_recovers_links_and_uncertain_uploads(cloud: _CloudState, tmp_pat
result = _run_script(_script_env(tmp_path, cloud.gateway_url), source)
assert result.returncode == 0, result.stdout + result.stderr
assert len(cloud.tasks) == 1
- assert cloud.upload_attempts["cloud_1/f1"] == (2 if failure in {"transient_upload", "expired_upload"} else 1)
+ assert cloud.upload_attempts["cloud_1/f1"] == (2 if failure == "transient_upload" else 1)
assert all(auth is None for surface, _, _, auth in cloud.requests if surface == "storage")
- assert (tmp_path / "result.zip").is_file()
+ assert (tmp_path / "results/f1/a.zip").is_file()
@pytest.mark.parametrize("invalid", ["missing_id", "unknown_status"])
@@ -729,7 +740,7 @@ def test_invalid_success_response_does_not_upload_or_poll(cloud: _CloudState, tm
assert result.returncode == 1
assert not cloud.upload_attempts
assert not any(method == "GET" for _, method, _, _ in cloud.requests)
- assert not (tmp_path / "result.zip").exists()
+ assert not (tmp_path / "results/f1/a.zip").exists()
@pytest.mark.parametrize("status,exit_code", [("partial", 2), ("failed", 1), ("running", 124)])
@@ -738,9 +749,22 @@ def test_client_exit_codes_and_poll_budget(cloud: _CloudState, tmp_path: Path, s
cloud.forced_status = status
source = tmp_path / "a.html"
source.write_bytes(HTML)
- result = _run_script(_script_env(tmp_path, cloud.gateway_url, MAX_POLLS="2"), source)
+ second = tmp_path / "b.html"
+ second.write_bytes(HTML + b"<!--second-->")
+ result = _run_script(_script_env(tmp_path, cloud.gateway_url, MAX_POLLS="2"), source, second)
assert result.returncode == exit_code, result.stdout + result.stderr
assert len(cloud.tasks) == 1 and "task_id=cloud_1" in result.stderr
- assert (tmp_path / "result.zip").exists() == (status == "partial")
+ assert (tmp_path / "results/f1/a.zip").exists() == (status == "partial")
if status == "running":
assert "continues running" in result.stderr
+
+
+def test_client_does_not_renew_expired_upload(cloud: _CloudState, tmp_path: Path) -> None:
+ """过期上传是该文件的终态,查询不能换发链接或重新创建任务。"""
+ cloud.expired_upload = True
+ source = tmp_path / "a.html"
+ source.write_bytes(HTML)
+ result = _run_script(_script_env(tmp_path, cloud.gateway_url), source)
+ assert result.returncode == 1, result.stdout + result.stderr
+ assert len(cloud.tasks) == 1 and cloud.upload_attempts == {"cloud_1/f1": 1}
+ assert not (tmp_path / "results/f1/a.zip").exists()
diff --git a/tests/unittest/test_task_outputs.py b/tests/unittest/test_task_outputs.py
new file mode 100644
index 00000000..486fab54
--- /dev/null
+++ b/tests/unittest/test_task_outputs.py
@@ -0,0 +1,206 @@
+"""验证 Tasks 的全部格式组合、单文件完整性和图片所有权。"""
+
+from __future__ import annotations
+
+import base64
+import io
+import itertools
+import json
+import re
+import zipfile
+from copy import deepcopy
+from pathlib import Path
+from typing import Any
+
+import pytest
+from bs4 import BeautifulSoup
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from PIL import Image
+from test_task_api import HTML, _submit, _terminal, _upload, service as task_service
+
+from mineru.parser import api_server
+from mineru.parser.base import ParseResult
+from mineru.types import (
+ EquationBlock,
+ ImageBlock,
+ ImageBodyBlock,
+ MiddleJson,
+ PageInfo,
+ TableBlock,
+ TableBodyBlock,
+ TextBlock,
+ TextSpan,
+)
+
+service = task_service
+
+COMBINATIONS = [
+ list(values) for size in range(1, 5) for values in itertools.combinations(("default", "docx", "html", "latex"), size)
+]
+
+
+def _illustrated_result() -> tuple[ParseResult, bytes]:
+ """构造同时包含正文图、表格内图片和公式的严格语义结果。"""
+ buffer = io.BytesIO()
+ Image.new("RGB", (12, 8), (20, 80, 150)).save(buffer, format="PNG")
+ png = buffer.getvalue()
+ uri = "data:image/png;base64," + base64.b64encode(png).decode()
+ middle = MiddleJson(
+ pages=[
+ PageInfo(
+ page_idx=0,
+ blocks=[
+ TextBlock(type="text", index=0, content=[TextSpan(type="text", content="Export content")]),
+ ImageBlock(
+ type="image",
+ index=1,
+ content=[ImageBodyBlock(type="image_body", index=1, content="Figure", image_base64=uri)],
+ ),
+ TableBlock(
+ type="table",
+ index=2,
+ content=[
+ TableBodyBlock(
+ type="table_body",
+ index=2,
+ content=f'<table><tr><td>Cell</td><td><img src="{uri}"></td></tr></table>',
+ )
+ ],
+ ),
+ EquationBlock(type="equation", index=3, content=r"E=mc^2"),
+ ],
+ )
+ ],
+ is_full_document=True,
+ metadata={"file_suffix": "docx", "producer": {"name": "mineru", "version": "test"}},
+ )
+ return ParseResult(middle_json=middle), png
+
+
+def _check_html(content: bytes, png: bytes) -> None:
+ """确认正文和富文本图片均内嵌,并保留文字、表格和公式内容。"""
+ soup = BeautifulSoup(content, "html.parser")
+ images = soup.find_all("img")
+ assert len(images) >= 2
+ assert all(image["src"].startswith("data:image/") for image in images)
+ assert all(base64.b64decode(image["src"].split(",", 1)[1]) == png for image in images)
+ assert "Export content" in soup.get_text() and "Cell" in soup.get_text()
+ assert "E=mc^2" in str(soup)
+
+
+def _check_docx(content: bytes, png: bytes) -> None:
+ """检查真正的 OOXML 图片及关系,不把外链或只有 ZIP 外壳当作 DOCX。"""
+ with zipfile.ZipFile(io.BytesIO(content)) as archive:
+ names = archive.namelist()
+ media = [name for name in names if name.startswith("word/media/")]
+ assert media and all(archive.read(name) == png for name in media)
+ assert b"Export content" in archive.read("word/document.xml")
+ assert b"Cell" in archive.read("word/document.xml")
+ assert b'TargetMode="External"' not in archive.read("word/_rels/document.xml.rels")
+
+
[email protected]("formats", COMBINATIONS, ids=lambda values: "+".join(values))
+def test_all_task_output_combinations(
+ service: tuple[TestClient, FastAPI], monkeypatch: pytest.MonkeyPatch, formats: list[str]
+) -> None:
+ """四种格式的十五种组合都只解析一次,产物完整并共享外置图片目录。"""
+ client, _ = service
+ result, png = _illustrated_result()
+ original = deepcopy(result.middle_json)
+ calls = 0
+
+ async def parse_one(*args: Any, **kwargs: Any) -> ParseResult:
+ """仅隔离输入分析,真实渲染、保存、Files 下载和 Router 转发全部保留。"""
+ nonlocal calls
+ calls += 1
+ return result
+
+ monkeypatch.setattr(api_server, "parse_async", parse_one)
+ task = _submit(client, [("source.html", HTML)], output_formats=formats)
+ _upload(client, task, [("source.html", HTML)])
+ finished = _terminal(client, task)
+ assert finished["status"] == "completed", finished
+ assert calls == 1 and result.middle_json == original
+ downloaded = client.get(finished["files"][0]["result_url"])
+ assert downloaded.status_code == 200
+ if formats == ["html"]:
+ assert downloaded.headers["content-type"].startswith("text/html")
+ _check_html(downloaded.content, png)
+ return
+ if formats == ["docx"]:
+ assert downloaded.headers["content-type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
+ _check_docx(downloaded.content, png)
+ return
+ assert downloaded.headers["content-type"] == "application/zip"
+ with zipfile.ZipFile(io.BytesIO(downloaded.content)) as archive:
+ entries = {name: archive.read(name) for name in archive.namelist()}
+ assert not any(name.endswith(".zip") for name in entries)
+ assert "manifest.json" not in entries and "model_output.json" not in entries
+ expected = set()
+ if "default" in formats:
+ expected.update({"markdown.md", "middle_json.json", "structured_content.json"})
+ for fmt, name in (("html", "document.html"), ("docx", "document.docx"), ("latex", "document.tex")):
+ if fmt in formats:
+ expected.add(name)
+ assert {name for name in entries if not name.startswith("images/")} == expected
+ if "default" in formats or "latex" in formats:
+ pictures = {name for name in entries if name.startswith("images/") and name != "images/"}
+ assert pictures and all(entries[name] == png for name in pictures)
+ if "default" in formats:
+ middle = json.loads(entries["middle_json.json"])
+ serialized = json.dumps(middle)
+ assert "data:image/" not in serialized and "image_base64" not in serialized
+ assert "Export content" in entries["markdown.md"].decode()
+ for name in re.findall(r'"image_path": "([^"]+)"', serialized):
+ assert name in pictures
+ if "latex" in formats:
+ tex = entries["document.tex"].decode()
+ assert "E=mc^2" in tex
+ assert r"\includegraphics" in tex
+ assert any(name in tex for name in pictures)
+ else:
+ assert not any(name.startswith("images/") for name in entries)
+ if "html" in formats:
+ _check_html(entries["document.html"], png)
+ if "docx" in formats:
+ _check_docx(entries["document.docx"], png)
+
+
[email protected]("formats", [["docx"], ["html"], ["default"], ["latex"]])
+def test_task_formats_use_only_service_authentication(tmp_path: Path, formats: list[str]) -> None:
+ """启用 Key 时四种格式都需要服务认证,通过认证后都可执行。"""
+ app = api_server.create_app(upload_dir=str(tmp_path), tier="flash", api_key="secret")
+ with TestClient(app) as client:
+ body = {"manifest": [{"client_file_id": "f1", "filename": "a.html", "bytes": len(HTML)}], "output_formats": formats}
+ assert client.post("/v1/tasks", json=body).status_code == 401
+ headers = {"Authorization": "Bearer secret"}
+ task = _submit(client, [("a.html", HTML)], output_formats=formats, headers=headers)
+ _upload(client, task, [("a.html", HTML)], headers=headers)
+ assert _terminal(client, task, headers=headers)["status"] == "completed"
+
+
+def test_duplicate_formats_and_missing_images(service: tuple[TestClient, FastAPI], monkeypatch: pytest.MonkeyPatch) -> None:
+ """重复格式归一化,缺失素材不能输出伪成功的多格式文件。"""
+ client, _ = service
+ task = _submit(client, [("a.html", HTML)], output_formats=["html", "html"])
+ assert task["output_formats"] == ["html"]
+ _upload(client, task, [("a.html", HTML)])
+ completed = _terminal(client, task)
+ assert client.get(completed["files"][0]["result_url"]).headers["content-type"].startswith("text/html")
+ broken, _ = _illustrated_result()
+ block = broken.middle_json.pages[0].blocks[1].content[0]
+ block.image_base64 = None
+ block.image_path = "images/missing.png"
+
+ async def missing_asset(*args: Any, **kwargs: Any) -> ParseResult:
+ """保留悬空素材引用,验证真实导出预检会阻止发布。"""
+ return broken
+
+ monkeypatch.setattr(api_server, "parse_async", missing_asset)
+ task = _submit(client, [("a.html", HTML)], output_formats=["default", "html"])
+ _upload(client, task, [("a.html", HTML)])
+ failed = _terminal(client, task)
+ assert failed["status"] == "failed"
+ assert failed["files"][0]["result_url"] is None
+ assert failed["files"][0]["error"]["code"] == "result_packaging_failed"