Skip to content

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

refactor(api): split task responses and unify file IDs

myhlolid3dd75821f0a
diff --git a/docs/en/usage/http_api.md b/docs/en/usage/http_api.md
index c785c4ba..22ef7675 100644
--- a/docs/en/usage/http_api.md
+++ b/docs/en/usage/http_api.md
@@ -10,21 +10,21 @@ OUTPUT_FORMATS=default,docx MINERU_API_URL=http://127.0.0.1:8000 bash scripts/ht
## Create and upload
-Send application/json to POST `/v1/tasks`. Each `files` entry requires `file_name` and, for uploaded files, `bytes`; `sha256sum`, `page_range`, and `client_file_id` are optional. Omitted or null IDs are assigned the smallest available `fN`, starting at `f1`, in input order after reserving all explicit IDs. IDs remain stable in task responses and upload links. URL entries may omit bytes. Options are tier, ocr_mode, page_range and output_formats.
+Send application/json to POST `/v1/tasks`. Each files entry requires file_name and, for uploads, bytes; sha256sum and page_range are optional. URL entries may omit bytes. Requests must not include client_file_id or file_id, even as null. The server generates a unique file_id for every entry and returns entries in input order. This ID remains stable through upload, query, cancellation and result download. Options are tier, ocr_mode, page_range and output_formats.
The response contains task_id and an upload object on each file that still needs uploading. files[].upload is null otherwise; its fields are url, headers and expires_at. Uploads always use PUT; upload_method is not returned. Follow each returned PUT URL and its headers; no completion request is needed. Each ready file enters pending independently. waiting-file covers upload, server-side download and validation; only a non-null upload object asks the client to send bytes. Input preparation consumes no parsing slot.
Loopback requests follow the same protocol. The SDK computes SHA-256 before submission; completed, unexpired cached inputs are not uploaded again. Concurrent first uploads may transfer duplicate bytes, but source storage is deduplicated. Default retention is 24 hours with collection every 5 minutes; active task and transfer references protect their bytes.
-Upload links expire one hour after task creation. Queries do not renew them. Uploads accepted before the deadline may finish. After an uncertain upload, query first. pending/running/completed need no upload; waiting-file with upload=null requires polling only. Retry only when an upload target is available, within the transfer retry budget. A successful PUT is not repeated while waiting for confirmation.
+Upload links expire one hour after task creation. Queries do not renew them. Uploads accepted before the deadline may finish. After an uncertain upload, query first. pending/running/completed need no upload; waiting-file with no upload field requires polling only. Retry only when an upload target is available, within the transfer retry budget. A successful PUT is not repeated while waiting for confirmation.
## Status and results
-Poll GET `/v1/tasks/{task_id}` using the configured API base, preserving its path prefix and URL-encoding the task ID. Match files by client_file_id. Parent states are waiting-file, pending, running, completed, partial, failed and canceled. Files use the same states except partial; upload_status has been removed. Each completed file has one files[].result_url; there is no top-level result_url or combined batch ZIP. Completed files can be downloaded while other files are still pending.
+Poll GET `/v1/tasks/{task_id}` using the configured API base, preserving its path prefix and URL-encoding the task ID. Bind the creation receipt to inputs in order, then match files by file_id. Parent states are waiting-file, pending, running, completed, partial, failed and canceled. Files use the same states except partial; upload_status has been removed. Each completed file has one files[].result_url; there is no top-level result_url or combined batch ZIP. Completed files can be downloaded while other files are still pending.
Outputs are default (Markdown, Middle JSON, Structured Content and images in a ZIP), docx, html, or latex (TEX and images in a ZIP). Multiple formats share one flat ZIP. DOCX and HTML embed images. ModelJson stays inside parsing and postprocessing; API, SDK, CLI and Gradio results do not include model output. The removed include_model_output option is rejected with HTTP 400, including false.
-Task and file listing endpoints have been removed. DELETE `/v1/tasks/{task_id}` cancels unfinished files. Files metadata, output download and deletion by ID remain available. Before completion, files[].parse is null. Successful files report their actual tier, duration_ms and parser_version; there is no response-level tier. Responses no longer echo per-file sha256sum, page_range, file_id or name. Request parameters remain available.
+Task and file listing endpoints have been removed. POST `/v1/tasks/{task_id}/cancel` cancels unfinished files. Files metadata and output download remain available; task-record and artifact deletion endpoints are not provided. Before completion, files[].parse is omitted. Successful files report their actual tier, duration_ms and parser_version; there is no response-level tier. Responses no longer echo per-file sha256sum, page_range, private source IDs or duplicate name fields. Request parameters remain available.
Use returned result URLs directly. Local servers and Router return Files URLs; SaaS may return signed storage URLs. Attach the API key only to same-origin API requests and reevaluate credentials at every redirect. Query the task again when a result signature expires.
@@ -35,3 +35,5 @@ Both shell examples delegate to the standard-library Python Tasks client. RESULT
Creation is not automatically retried. MAX_POLLS/POLL_INTERVAL bound polling; CONNECT_TIMEOUT/REQUEST_TIMEOUT bound individual requests. Exit codes are 0 (success), 2 (partial success), 1 (failure or cancellation) and 124 (poll budget exhausted). Completed downloads remain on disk.
Tasks and Files JSON use `file_name`; creation accepts `files`. Old `manifest`/`filename` fields and mixed old/new fields are rejected with 400. The standalone upload and Jobs APIs have been removed. Coordinate server, Router and SDK upgrades; see [migration notes](../../next/api/changes.md). The separate [file_parse wrapper](../../next/api/file-parse.md) provides recoverable synchronous single-file calls.
+
+POST returns a creation receipt, GET returns task details, POST cancel returns every file’s final state and successful result links, and local PUT returns task_id/file_id/status. Tasks success responses omit null fields but preserve zero values and empty collections. POST cancel cancels unfinished files while preserving completed results.
diff --git a/docs/next/api/README.md b/docs/next/api/README.md
index 86b0c11c..259c2a9d 100644
--- a/docs/next/api/README.md
+++ b/docs/next/api/README.md
@@ -46,9 +46,8 @@ ID 使用 OpenAI 风格的前缀加随机串。官方 API 使用 24 字符 base6
| `GET` | `/v1/tiers` | 列出解析档位 |
| `GET` | `/v1/files/{file_id}` | 查询文件元信息 |
| `GET` | `/v1/files/{file_id}/content` | 下载解析产物 |
-| `DELETE` | `/v1/files/{file_id}` | 删除文件 |
| `POST` | `/v1/tasks` | JSON 清单创建任务,返回缺失文件上传链接 |
-| `DELETE` | `/v1/tasks/{task_id}` | 取消未完成文件 |
+| `POST` | `/v1/tasks/{task_id}/cancel` | 取消未完成文件 |
| `GET` | `/v1/tasks/{task_id}` | 查询总状态和逐文件状态,取得每个成功文件的下载链接 |
| `PUT` | 返回的上传链接 | 每个链接上传一个文件 |
| `POST` | `/v1/chat/completions` | Chat Completions 文档对话 |
@@ -58,7 +57,7 @@ ID 使用 OpenAI 风格的前缀加随机串。官方 API 使用 24 字符 base6
JSON、逐文件上传、独立结果链接与 Router 负载规则见 [V1 tasks](tasks.md)。SaaS 可以独立实现同一契约,并返回 OSS 直链;客户端不要求其实现本地 Files 下载路由。
各接口的成功状态码、Content-Type 和返回对象见 [响应总览](responses.md#成功响应)。
-创建、查询、取消及本地上传均返回完整的 [TaskStatusResponse](tasks.md#taskstatusresponse);列表返回分页摘要,Files 下载返回二进制附件。
+创建、查询、取消及本地上传分别返回独立的[响应模型](tasks.md#响应模型),Tasks 成功响应省略无值可选字段;Files 下载返回二进制附件。
需要单文件直传和同步附件响应时,可另外启动 [file_parse 包装服务](file-parse.md),它提供自己的 `/v1/file_parse`、查询和下载接口,并通过上面的 Tasks 协议连接任意部署。
diff --git a/docs/next/api/changes.md b/docs/next/api/changes.md
index 3e9780ed..c779a9a0 100644
--- a/docs/next/api/changes.md
+++ b/docs/next/api/changes.md
@@ -6,9 +6,9 @@
|---|---|
| Tasks 创建请求 `manifest` | `files`,仍为 1–100 项数组;旧字段或新旧混传返回 400。 |
| Tasks / Files JSON `filename` | `file_name`;下载附件命名规则保持不变。 |
-| 创建请求必填 `client_file_id` | 可省略或为 `null`;服务端按输入顺序补全最小可用的 `fN`,避开所有显式 ID,响应仍必填。 |
+| 创建请求 `client_file_id` | 字段移除;请求也禁止指定 file_id,包括 null。服务端统一生成公共 file_id,响应按输入顺序返回。 |
| 创建 Upload、PUT、complete | POST `/v1/tasks` 提交清单,只 PUT 缺失文件;上传成功自动排队。 |
-| 创建、查询、取消 Job | POST `/v1/tasks`;按 task_id GET/DELETE,不提供任务列表。 |
+| 创建、查询、取消 Job | POST `/v1/tasks` 创建,GET `/v1/tasks/{task_id}` 查询,POST `/v1/tasks/{task_id}/cancel` 取消;不提供任务列表。 |
| `files[].output_files` | `files[].result_url`,每个输入一个完整产物链接。 |
| `markdown/middle_json/structured_content/zip` 输出选项 | `default` 默认 ZIP;另可组合 `docx/html/latex`。 |
| `local/inline/file_id` 输入 | 文件上传或 URL;同机先计算 hash,缓存未命中也需上传。 |
@@ -18,18 +18,27 @@
| 响应 `uploads/pending_uploads` | 改为各个 `files[].upload`,子字段为 `url/headers/expires_at`,不重复携带文件 ID;上传路由路径仍含 `/uploads/`。 |
| Tasks `status_url` | 删除,客户端使用配置的 API 基址和编码后的 task_id 构造固定查询路由。 |
| 响应顶层 `tier` | 改为成功文件的 `files[].parse.tier`,取实际结果元数据;请求 tier 仍保留。 |
-| 响应 `files[].sha256sum/page_range/file_id/name` | 删除;请求 hash 和页范围不变,源引用只在内部管理。 |
+| 响应源文件 `file_id` 与 `client_file_id` | 原源资源 ID 不再公开;新 files[].file_id 从创建到产物保持不变,并与结果 Files ID 一致。源缓存仍为私有引用。 |
+| 响应 `files[].sha256sum/page_range/name` | 删除;请求 hash 和页范围不变。 |
+| 共用 `TaskStatusResponse` | 分为 CreateTaskResponse、TaskDetailResponse、CancelTaskResponse、UploadFileResponse;GET 扩展不进入其他响应。 |
+| Tasks 成功响应的 null 占位字段 | 省略无值可选字段,保留零值和空集合;file_parse 自身及共享错误 envelope 保持现状。 |
| `upload_status` | 删除;仅保留 files[].status。waiting-file 统一输入准备,pending 表示已就绪后的解析排队。 |
-| 状态 `waiting_upload/queued` | 改为 `waiting-file/pending`,不提供旧值别名;等待文件且 upload=null 时只轮询。 |
+| 状态 `waiting_upload/queued` | 改为 `waiting-file/pending`,不提供旧值别名;等待文件且没有 upload 时只轮询。 |
| `upload_method` | 字段删除,客户端固定使用 PUT,并原样使用 URL 和请求头。 |
-| `files[].parse.model_used` | 删除;成功后的 parse 包含 `tier/duration_ms/parser_version`,完成前为 null。 |
+| `files[].parse.model_used` | 删除;成功后的 parse 包含 `tier/duration_ms/parser_version`,完成前省略。 |
-`--allow-local-source` 和 `--max-inline-bytes` 同时删除。Files 按 ID 查询、下载与删除、Health、Tiers、Models、Usage 保留;同步 `file_parse` 继续作为独立包装服务运行。
+`--allow-local-source` 和 `--max-inline-bytes` 同时删除。Files 按 ID 查询和下载、Health、Tiers、Models、Usage 保留;同步 `file_parse` 继续作为独立包装服务运行。
SDK 保留 `MinerUApiParser` 方法和返回类型,状态类型改为 `ApiTaskStatus`,保留 `ApiJobStatus` Python 别名。直接本地 parser 与 HF CPU/ZeroGPU 内嵌解析不经过 HTTP。
停收旧请求、等待在途任务完成,再协调升级 worker、Router、SDK、file_parse 包装服务和应用。SaaS Go 服务需部署方按同一契约配套更新;进程内任务和缓存索引不保证跨重启恢复。
Router 通过候选 worker 的 `/v1/usage` 校验认证,不再依赖 Files 列表。
-file_parse 恢复状态 namespace 增加 `tasks-v4-` 前缀,旧 `tasks-v3-`、`tasks-v2-` 及无前缀记录目录保留但不加载;新空间内继续支持 request_id 幂等和重启恢复。不提供旧客户端或旧 worker 的协议回退。
+file_parse 恢复状态 namespace 增加 `tasks-v5-` 前缀,旧 `tasks-v4-`、`tasks-v3-`、`tasks-v2-` 及无前缀记录目录保留但不加载;新空间内继续支持 request_id 幂等和重启恢复。不提供旧客户端或旧 worker 的协议回退。
Router 源缓存与下游源 Files ID 解耦,仍保留结果 Files 映射和结果租约。file_parse 自身基于 request_id 的 status_url 不属于 Tasks 响应,本次保持不变。
+
+公共 file_id 在创建时预留;产物生成前访问对应 Files 元数据或内容接口均返回 404。产物完成后,下载地址使用相同 ID。Router 按层保存公共 ID 与下游 ID 的映射,不要求不同服务层使用相同字符串。
+
+file_parse 获得创建回执后先持久化 task_id/file_id,再查询详情。首次 GET 失败或随后重启不会重复创建;仅创建请求的结果未知时进入 submission_unknown。
+
+取消入口改为 `POST /v1/tasks/{task_id}/cancel`,继续返回 200 和逐文件终态;不保留 DELETE 取消别名。任务记录和产物的公开 DELETE 接口均不提供,在认证通过后返回 405。内部保留期回收、缓存引用释放及活动下载保护保持不变。
diff --git a/docs/next/api/examples.md b/docs/next/api/examples.md
index a4e41758..b5cfcf3e 100644
--- a/docs/next/api/examples.md
+++ b/docs/next/api/examples.md
@@ -11,10 +11,10 @@ TASK_ID=job_... MINERU_API_URL=http://127.0.0.1:8000 bash scripts/http_task_exam
直接提供 URL 时只需提交 JSON:
```json
-{"files":[{"client_file_id":"report","file_name":"report.pdf","url":"https://example.com/report.pdf"}],"output_formats":["default"]}
+{"files":[{"file_name":"report.pdf","url":"https://example.com/report.pdf"}],"output_formats":["default"]}
```
对 `/v1/tasks` 执行 POST,保存返回的 `task_id`。本地文件清单包含 `bytes` 和可选 `sha256sum`;只对 `files[].upload` 非空的文件,使用其中的 `url/headers` 发送 PUT。
-完成后下载对应 `files[].result_url`。使用 API 基址和编码后的 task_id 构造 `GET /v1/tasks/{task_id}` 查询任务,取消使用 `DELETE /v1/tasks/{task_id}`;不提供任务列表。
+完成后下载对应 `files[].result_url`。使用 API 基址和编码后的 task_id 构造 `GET /v1/tasks/{task_id}` 查询任务,取消使用 `POST /v1/tasks/{task_id}/cancel`;不提供任务列表。
详见 [Tasks 契约](tasks.md)、[SDK](../sdk/api-parser.md) 和 [同步包装服务](file-parse.md)。
diff --git a/docs/next/api/file-parse.md b/docs/next/api/file-parse.md
index 12a8cb7d..2983e4fa 100644
--- a/docs/next/api/file-parse.md
+++ b/docs/next/api/file-parse.md
@@ -54,7 +54,7 @@ curl --max-time 7200 -D response.headers -o response.body \
## 响应结构与格式
-以下三个接口均属于独立 file_parse 包装服务。它们的 JSON 状态对象是下文的 `StatusResponse`,不是 Tasks 的 `TaskStatusResponse`。
+以下三个接口均属于独立 file_parse 包装服务。它们的 JSON 状态对象是下文的 `StatusResponse`,独立于 Tasks 的创建、详情和取消响应模型。
| 接口 | HTTP | Content-Type | 正文格式 |
|---|---|---|---|
@@ -116,7 +116,7 @@ X-Task-ID: job_0123456789abcdef01234567
|---|---|
| `prepared` | 本地源文件和恢复记录已持久化,尚未开始提交。 |
| `submitting` | 正在向上游创建任务,尚无确认后的 `task_id`。 |
-| `waiting-file` | 上游仍在接收、下载、校验或确认输入;upload=null 不表示已经就绪。 |
+| `waiting-file` | 上游仍在接收、下载、校验或确认输入;上游省略 upload 不表示已经就绪。 |
| `pending` | 已进入上游执行队列。 |
| `running` | 上游正在解析或导出。 |
| `completed` | 上游完整产物已生成,可通过包装服务下载。 |
@@ -328,4 +328,6 @@ python scripts/http_file_parse_example.py report.pdf --wait-timeout 0 \
## 升级与恢复记录
本次协议升级要求 API Server、Router、SDK、Gradio 与包装服务同步更新,先停收请求并排空旧任务。
-恢复记录目录使用 `tasks-v4-` 加既有上游地址与认证摘要,不加载、不迁移也不自动删除旧 `tasks-v3-`、`tasks-v2-` 或无前缀目录。包装服务自身的 `status_url` 与 Location 头保持不变,上游 Tasks 查询改用固定路径。旧 request_id 不再恢复;新空间内继续支持幂等和进程重启恢复。
+恢复记录目录使用 `tasks-v5-` 加既有上游地址与认证摘要,不加载、不迁移也不自动删除旧 `tasks-v4-`、`tasks-v3-`、`tasks-v2-` 或无前缀目录。包装服务自身的 `status_url` 与 Location 头保持不变,上游 Tasks 查询改用固定路径。旧 request_id 不再恢复;新空间内继续支持幂等和进程重启恢复。
+
+上游 POST 只返回创建回执。包装服务先持久化服务端生成的 task_id/file_id 和原始请求上下文,再 GET 查询详情;查询失败或重启仍恢复同一任务,不重放创建。只有 Tasks 成功响应省略 null,本文的 StatusResponse、status_url 和错误响应保持原规则。
diff --git a/docs/next/api/files.md b/docs/next/api/files.md
index b917913e..7a76e3f3 100644
--- a/docs/next/api/files.md
+++ b/docs/next/api/files.md
@@ -6,7 +6,6 @@ Files 保存源文件视图与已生成的结果,不提供文件列表。异
|---|---|---|
| GET | `/v1/files/{file_id}` | 返回文件元数据。 |
| GET | `/v1/files/{file_id}/content` | 流式下载已保存的解析产物;源文件不提供公共下载。 |
-| DELETE | `/v1/files/{file_id}` | 删除文件视图;正在执行和下载的引用继续受保护。 |
## FileObject:文件元数据
@@ -43,22 +42,15 @@ Files 的时间字段为 Unix 秒级整数,与 Tasks 的 ISO-8601 时间字符
}
```
-示例中的 ID、大小、时间和 hash 为示意值。本地源文件元数据使用相同结构,`purpose` 为 `parse`,`file_name` 为输入文件名。Tasks 不公开源 Files ID;Router 仅登记结果的公共 Files 映射。
+示例中的 ID、大小、时间和 hash 为示意值。本地源文件元数据使用相同结构,`purpose` 为 `parse`,`file_name` 为输入文件名。Tasks 不公开源缓存 ID;创建响应中的 files[].file_id 即本次解析结果的公共 Files ID,Router 将它映射到 worker 的结果 ID。Tasks 的 file_name/bytes 描述输入,Files 的 file_name/bytes 描述实际产物。
-## DELETE /v1/files/{file_id}:删除文件视图
+产物生成前只预留 ID,不注册 Files 对象:GET 元数据和 GET content 均返回 404 file_not_found。创建任务的 ID 预留不代表产物已经存在,准备与执行状态通过 GET Tasks 查询。
-成功返回 **`200 OK` + `application/json`**,正文不是 `FileObject`,而是以下删除确认:
+## 产物保留与清理
-```json
-{
- "id": "file-result0123456789abcdef",
- "object": "file",
- "deleted": true
-}
-```
-
-三个字段均必带且不可为 `null`:`id` 为请求的文件 ID,`object` 固定为 `file`,`deleted` 为布尔值。
-这与取消 Task 不同:`DELETE /v1/tasks/{task_id}` 返回完整任务快照,不返回 `deleted`。
+当前不提供产物删除接口,`DELETE /v1/files/{file_id}` 在认证通过后返回 `405 Method Not Allowed`。
+任务取消使用 `POST /v1/tasks/{task_id}/cancel`,保留已完成的产物和下载链接;取消任务不会删除这些资源。
+产物按既有保留期由内部机制自动回收,活动执行、下载引用和 Router 租约继续受保护。
## GET /v1/files/{file_id}/content:下载结果
diff --git a/docs/next/api/responses.md b/docs/next/api/responses.md
index 7d911bbf..2e66faac 100644
--- a/docs/next/api/responses.md
+++ b/docs/next/api/responses.md
@@ -7,33 +7,24 @@
## 成功响应
-成功响应直接返回接口定义的对象,不增加统一外层 envelope。资源对象、分页列表、文件删除确认及二进制附件是不同的返回类型,不能统一按 Task 对象解析。
+成功响应直接返回接口定义的对象,不增加统一外层 envelope。资源对象、分页列表及二进制附件是不同的返回类型,不能统一按 Task 对象解析。
| 接口 | 成功 HTTP | Content-Type | 正文 |
|---|---|---|---|
-| `POST /v1/tasks` | 202 | `application/json` | 完整 `TaskStatusResponse`。 |
-| `GET /v1/tasks/{task_id}` | 200 | `application/json` | 完整 `TaskStatusResponse`,包括失败或取消后的状态。 |
-| `DELETE /v1/tasks/{task_id}` | 200 | `application/json` | 取消后的完整 `TaskStatusResponse`,不是删除确认。 |
-| 本地 `PUT /v1/tasks/{task_id}/uploads/{client_file_id}` | 200 | `application/json` | 当前完整 `TaskStatusResponse`。对象存储上传由存储服务定义响应。 |
+| `POST /v1/tasks` | 202 | `application/json` | `CreateTaskResponse`:task_id、status、files 创建回执。 |
+| `GET /v1/tasks/{task_id}` | 200 | `application/json` | `TaskDetailResponse`,包括失败或取消后的完整详情。 |
+| `POST /v1/tasks/{task_id}/cancel` | 200 | `application/json` | `CancelTaskResponse`:task_id、status、finished_at 和全部文件终态,保留成功产物链接。 |
+| 本地 `PUT /v1/tasks/{task_id}/uploads/{file_id}` | 200 | `application/json` | `UploadFileResponse`:task_id、file_id 和该文件 status。对象存储上传接受其成功 2xx 响应。 |
| `GET /v1/files/{file_id}` | 200 | `application/json` | 完整 `FileObject`。 |
-| `DELETE /v1/files/{file_id}` | 200 | `application/json` | `id/object/deleted` 删除确认。 |
| `GET /v1/files/{file_id}/content` | 200(完整下载) | 随产物格式 | ZIP、DOCX 或 HTML 文件字节。 |
| 独立 `POST /v1/file_parse` | 200 / 202 | 附件 MIME / `application/json` | 等待成功返回附件;等待到期或零等待返回包装层 `StatusResponse`。 |
-| 独立 `GET /v1/file_parse/{request_id}` | 200 | `application/json` | 包装层 `StatusResponse`,不是 `TaskStatusResponse`。 |
+| 独立 `GET /v1/file_parse/{request_id}` | 200 | `application/json` | 包装层 `StatusResponse`,独立于 Tasks 的响应模型。 |
| 独立 `GET /v1/file_parse/{request_id}/result` | 200 | 随产物格式 | ZIP、DOCX 或 HTML 文件字节。 |
-Tasks 全部响应字段、类型、可空值及各接口完整 JSON 见 [Tasks](tasks.md#taskstatusresponse);Files 和下载响应见 [Files](files.md)。
+Tasks 各响应模型、字段省略规则及完整 JSON 见 [Tasks](tasks.md#响应模型);Files 和下载响应见 [Files](files.md)。
Health、Models、Tiers 见 [能力发现接口](health-models.md),用量见 [Usage](usage-limits.md),独立 Chat/Responses 协议见 [文档对话](chat.md)。
独立包装服务的附件、202、状态查询和错误结构见 [file_parse 响应说明](file-parse.md#响应结构与格式)。
-JSON 正文使用 UTF-8;可空字段使用 JSON `null`,空列表使用 `[]`。例如删除一个 File 的成功响应为:
-
-```json
-{
- "id": "file-result0123456789abcdef",
- "object": "file",
- "deleted": true
-}
-```
+JSON 正文使用 UTF-8。Tasks 成功响应省略无值可选字段,保留 0、false、[] 和 {};其他接口及非成功错误 envelope 沿用各自的 null 规则。任务取消使用 `POST /v1/tasks/{task_id}/cancel`;目前不提供任务记录或产物的公开删除接口。
当前 Python API Server 和 Router 不统一生成或返回 `X-Request-Id`;网关或公网部署提供请求追踪时,客户端可记录该响应头,不能把它作为上述共同响应的必带头。
独立 file_parse 的成功附件和 202 响应明确携带 `X-Request-ID`;其状态查询和错误响应不统一附加该头,以专页列出的条件为准。
diff --git a/docs/next/api/tasks.md b/docs/next/api/tasks.md
index 393942e6..4be0ca9e 100644
--- a/docs/next/api/tasks.md
+++ b/docs/next/api/tasks.md
@@ -5,21 +5,22 @@
每个文件就绪后立即执行,完成后在 `files[].result_url` 返回独立下载链接。
客户端不拼接存储路径,也不要求 SaaS 实现本地 Files API。
-快速定位:[响应字段](#taskstatusresponse) · [各接口成功响应](#各接口成功响应) · [错误响应](#各接口错误响应) · [输出格式与下载](#输出格式与下载)。
+快速定位:[响应字段](#响应模型) · [各接口成功响应](#各接口成功响应) · [错误响应](#各接口错误响应) · [输出格式与下载](#输出格式与下载)。
## 路由与请求
| 方法与路径 | 行为 |
|---|---|
| `POST /v1/tasks` | 仅接受 `application/json`,返回 `202` 和稳定 `task_id`。 |
-| `PUT` 返回的 `files[].upload.url` | 每个链接上传一个文件;本地使用 `PUT /v1/tasks/{task_id}/uploads/{client_file_id}`。 |
+| `PUT` 返回的 `files[].upload.url` | 每个链接上传一个文件;本地使用 `PUT /v1/tasks/{task_id}/uploads/{file_id}`。 |
| `GET /v1/tasks/{task_id}` | 返回 `200`,包含总状态、逐文件状态、尚有效的上传链接和已完成文件的下载链接。 |
-| `DELETE /v1/tasks/{task_id}` | 返回 `200` 和取消后的完整任务对象,保留已经完成文件的下载链接。 |
+| `POST /v1/tasks/{task_id}/cancel` | 返回 `200 CancelTaskResponse`,包含所有文件的终态及已经完成文件的下载链接。 |
创建请求不再接受表单、multipart 或文件字节,其他 Content-Type 返回 `415`。
业务参数必须放在 JSON 主体中,POST 查询参数、未知字段、非法值返回 `400 invalid_request`。
上传文件的 PUT 仍发送原始字节,使用返回的 `files[].upload.headers`;签名 URL 必须原样使用。
Task ID 是父任务标识;内部逐文件执行 ID 不属于公共契约。
+不提供任务记录或产物的公开 DELETE 接口;旧 DELETE 取消入口不保留别名,认证通过后返回 405。
| JSON 字段 | 默认值 | 说明 |
|---|---|---|
@@ -35,17 +36,18 @@ ModelJson 仅用于内部解析与后处理,不属于 HTTP 或 SDK 结果。
| 字段 | 必填 | 说明 |
|---|---|---|
-| `client_file_id` | 否 | 任务内唯一,1–64 个字母、数字、下划线或短横线;省略或 `null` 时由服务端补全。 |
| `file_name` | 是 | 逻辑文件名,保留扩展名;不同条目允许同名。 |
| `url` | 否 | HTTP(S) 文件下载地址,受部署来源策略约束;省略或 `null` 表示客户端上传。 |
| `bytes` | 条件 | 上传项必填;URL 项可省略或为 `null`。提供时必须是严格正整数。 |
| `sha256sum` | 否 | 64 位小写十六进制 SHA-256;用于完整性校验,上传项还用于源文件缓存预检。 |
| `page_range` | 否 | 逐文件 PDF 页范围,未提供时继承全局值;非 PDF 仍只支持整本解析。 |
-服务端先预留全部显式 `client_file_id`,再按缺省项的输入顺序,从 `f1` 开始分配最小未占用的 `fN`。例如显式占用了 `f2`,两项缺省 ID 分别生成 `f1`、`f3`。空字符串、非法 ID 和重复显式 ID 返回 400。
-创建响应的 `files` 顺序与输入一致,`files[]` 始终返回非空 ID;上传描述直接位于对应文件的 `upload`,不重复携带 ID。生成后的文件标识在上传、查询及 Router 转发中保持不变。
+服务端为每个输入分配唯一的 `file_id`,请求不得包含 `client_file_id` 或 `file_id`,即使值为 `null` 也返回 `400 invalid_request`。
+创建响应的 `files` 顺序与输入一致,客户端先按原始顺序绑定 ID,随后使用 ID 关联上传、查询、取消和结果。同名输入或相同内容仍获得不同 ID。
+该 ID 从创建到结果下载保持不变;在本地和 Router 中,产物注册后的 Files ID 与它一致。产物生成前只预留 ID,对 Files 元数据和内容接口的访问返回 `404 file_not_found`。
+源缓存引用不属于公共 ID;跨任务可共享源字节,但每次任务独立生成产物。Router 内部映射各层生成的 ID,对客户端始终保留本层 ID。
-先从真实文件生成 JSON 请求(本例省略 ID,由服务端补全):
+先从真实文件生成 JSON 请求(文件 ID 统一由服务端生成):
```bash
python3 - a.pdf b.pdf > task.json <<'PY'
@@ -78,185 +80,158 @@ curl --fail-with-body "$MINERU_API_URL/v1/tasks" \
未配置 API Key 的本地服务可省略 Authorization,四种输出格式均可用;启用服务认证后四种格式均需认证,没有额外的格式权限限制。
-## TaskStatusResponse
+## 响应模型
-`POST /v1/tasks`、`GET /v1/tasks/{task_id}`、`DELETE /v1/tasks/{task_id}` 的成功响应均为完整的 `TaskStatusResponse`。
-本地逐文件上传 `PUT /v1/tasks/{task_id}/uploads/{client_file_id}` 也返回同一结构。成功时直接返回对象,没有 `data` 或 `task` 外层包装。
+创建、详情、取消和上传确认使用独立模型。成功响应直接返回对象,没有 `data` 或 `task` 包装。GET 新增详情字段不会自动进入其他响应。
-JSON 响应使用 `Content-Type: application/json`,正文为 UTF-8。下表列出的字段在当前本地 API Server 和 Router 响应中均会出现;可空字段输出 `null`,空集合输出 `[]` 或 `{}`,不以省略字段代替。客户端应忽略未来新增的响应字段。
-时间字符串使用 ISO-8601 UTC 格式,例如 `2026-10-23T04:00:00Z`;上传链接的 `expires_at` 单独使用 Unix 秒级整数。
-请求中的 `tier/ocr_mode/page_range` 与逐文件 `sha256sum/page_range` 不作响应回显;实际执行档位在成功文件的 `parse.tier` 中提供。
-客户端使用配置的 API 基址(包含代理前缀)追加 `/v1/tasks/{URL 编码后的 task_id}` 查询;响应不包含 `status_url`。
+| 接口 | 模型 | 顶层字段 |
+|---|---|---|
+| POST 创建 | `CreateTaskResponse` | `task_id/status/files`。 |
+| GET | `TaskDetailResponse` | `task_id/status/created_at/output_formats/progress/files`,以及有值的 `started_at/finished_at/error`。 |
+| POST cancel | `CancelTaskResponse` | `task_id/status/finished_at/files`。 |
+| 本地 PUT | `UploadFileResponse` | `task_id/file_id/status`,其中 status 是本次上传文件的状态。 |
-### 顶层字段
+这些成功响应递归省略值为 `null` 的可选字段,保留 `0/false/[]/{}`,例如 `progress.failed=0` 和 `upload.headers={}`。OpenAPI 将可省略字段标为非必填。
+每次响应是该接口当前的完整快照;缺少可选字段表示当前没有该值,不能沿用上一次响应的上传地址或结果信息。客户端应忽略未来新增的字段。
+共享的非成功错误响应,以及 Files、file_parse 自身的响应,保持各自现有空值规则。
-| 字段 | JSON 类型 | 可为 null | 含义 |
-|---|---|---|---|
-| `task_id` | string | 否 | 稳定的父任务 ID;是不透明标识,不代表内部逐文件执行 ID。 |
-| `status` | string | 否 | 父任务状态:`waiting-file/pending/running/completed/partial/failed/canceled`。 |
-| `created_at` | string | 否 | 父任务创建时间。 |
-| `started_at` | string | 是 | 已知的最早逐文件执行开始时间;尚无执行开始记录时为 `null`。 |
-| `finished_at` | string | 是 | 父任务进入终态的时间;非终态时为 `null`,取消成功时也会填写。 |
-| `output_formats` | array of string | 否 | 本次任务采用的输出格式,按首次出现去重。 |
-| `progress` | object | 否 | 文件计数,结构见下表。 |
-| `files` | array of object | 否 | 完整逐文件快照,顺序始终与创建请求一致,结构见下表。 |
-| `error` | object | 是 | 父任务级错误,结构为 `ErrorDetail`;逐文件失败应检查 `files[].error`。 |
-
-### progress:文件计数
+JSON 正文使用 UTF-8。时间字符串使用 ISO-8601 UTC;上传链接 `expires_at` 使用 Unix 秒级整数。
+请求中的 `tier/ocr_mode/page_range` 和逐文件 `sha256sum/page_range` 不作响应回显;实际档位位于成功文件的 `parse.tier`。
+客户端保留配置 API 基址的代理前缀,并追加 `/v1/tasks/{URL 编码后的 task_id}` 查询;Tasks 不返回 `status_url`。
-| 字段 | JSON 类型 | 含义 |
-|---|---|---|
-| `completed` | integer | 已成功完成解析和全部所选格式导出的文件数。 |
-| `failed` | integer | 已失败文件数,包含上传过期、下载、解析或导出失败。 |
-| `total` | integer | 输入文件总数,固定为创建请求的 `files` 长度。 |
+### 创建回执的 files[]
-取消的文件不计入 `completed` 或 `failed`。存在排队、运行、等待上传或已取消文件时,`completed + failed` 可以小于 `total`,包括父任务已经为 `canceled` 的情况。
+每项必带 `file_id/file_name/status`;只有当前需要客户端上传时才带 `upload`。POST 不返回文件大小、解析统计或结果链接,即使文件已经完成也通过 GET 获取详情。
-### files[]:逐文件对象
+### 查询详情的顶层字段
-| 字段 | JSON 类型 | 可为 null | 含义 |
+| 字段 | JSON 类型 | 必带 | 含义 |
|---|---|---|---|
-| `client_file_id` | string | 否 | 客户端显式提供或服务端补全的任务内唯一标识,创建后不变。 |
-| `file_name` | string | 否 | 创建时提交的逻辑文件名,保留扩展名;同名文件通过 ID 区分。 |
-| `bytes` | integer | 是 | 上传项的声明大小;URL 项可暂为 `null`,完整下载并校验后补齐实际字节数。 |
-| `url` | string | 是 | URL 输入保留原始下载地址;客户端上传项为 `null`。 |
-| `upload` | object | 是 | 当前可执行的客户端上传动作;服务端接收、下载、校验、输入已就绪或文件终结时为 `null`,结构见下表。 |
-| `status` | string | 否 | 单文件状态:`waiting-file/pending/running/completed/failed/canceled`;没有 `partial`。 |
-| `parse` | object | 是 | 解析成功完成后返回实际档位和统计;完成前、失败或取消的文件为 `null`。 |
-| `result_url` | string | 是 | 结果完整保存后发布的唯一下载 URL;非 `completed` 文件为 `null`。 |
-| `error` | object | 是 | 该文件的错误详情;无错误时为 `null`。 |
-
-逐文件仅使用一套 `status`:
-
-| 状态 | 含义 |
-|---|---|
-| `waiting-file` | 文件准备中,包含等待客户端上传、接收文件、对象存储确认、URL 下载及完整性校验。 |
-| `pending` | 输入已就绪,等待解析资源。 |
-| `running` | 解析、导出及保存结果中。 |
-| `completed` | 结果已保存,可通过 result_url 下载。 |
-| `failed` | 本次处理失败,原因见 error。 |
-| `canceled` | 已取消。 |
+| `task_id` | string | 是 | 稳定的父任务 ID,不代表内部逐文件执行 ID。 |
+| `status` | string | 是 | `waiting-file/pending/running/completed/partial/failed/canceled`。 |
+| `created_at` | string | 是 | 父任务创建时间。 |
+| `started_at` | string | 否 | 已知最早的逐文件执行开始时间,无记录时省略。 |
+| `finished_at` | string | 否 | 父任务进入终态的时间,非终态时省略。 |
+| `output_formats` | array of string | 是 | 本次输出格式,按首次出现去重。 |
+| `progress` | object | 是 | 必带整数 `completed/failed/total`,零值保留。 |
+| `files` | array of object | 是 | 全部文件的当前详情,始终保持创建请求顺序。 |
+| `error` | object | 否 | 父任务级错误,逐文件失败见 files[].error。 |
+
+`completed` 计数表示解析及全部所选格式均成功的文件数;`failed` 包含上传过期、下载、解析和导出失败;`total` 固定为输入文件数。取消文件不计入 completed 或 failed。
+
+### 查询详情的 files[]
+
+| 字段 | JSON 类型 | 必带 | 含义 |
+|---|---|---|---|
+| `file_id` | string | 是 | 服务端分配的公共文件 ID,创建后不变。 |
+| `file_name` | string | 是 | 输入逻辑文件名,同名文件通过 ID 区分。 |
+| `status` | string | 是 | `waiting-file/pending/running/completed/failed/canceled`,没有 partial。 |
+| `bytes` | integer | 否 | 输入大小,URL 下载前未知时省略,校验后补齐实际字节数。 |
+| `url` | string | 否 | URL 输入的原始下载地址,上传输入省略。 |
+| `upload` | object | 否 | 当前可执行的上传动作,服务端准备、输入就绪或终结时省略。 |
+| `parse` | object | 否 | 成功完成后的实际档位和解析统计。 |
+| `result_url` | string | 否 | completed 文件完整产物的下载地址。 |
+| `error` | object | 否 | 文件错误详情,无错误时省略。 |
-仅在 `waiting-file` 且 `upload` 非空时执行上传;`waiting-file` 且 `upload=null` 表示当前由服务端准备文件,客户端只轮询。
-成功 PUT 后即使仍为 `waiting-file` 也不重复传输。只有上传失败、查询确认仍需上传且链接有效时,才进行有界重试。
-缓存命中可以直接进入 `pending`。上传过期使用 `failed` 和 `error.code=upload_expired`,不另设过期状态;取消时 upload 为 null。
+`waiting-file` 包括等待上传、接收、对象存储确认、URL 下载及完整性校验;`pending` 表示输入已就绪并等待解析资源;`running` 包含解析、导出和结果保存。
+只在 `waiting-file` 且存在 `upload` 时上传;没有 upload 时只轮询,不能据此认为输入已经就绪。成功 PUT 后即使仍为 waiting-file 也不重复传输。
+只有上传失败、查询确认仍需上传且链接有效时才有界重试。上传过期使用 `failed` 和 `error.code=upload_expired`。
+
+### 取消回执的 files[]
+
+每项必带 `file_id/file_name/status`,status 只会是 `completed/failed/canceled`。成功文件附带 `parse/result_url`,失败文件附带 `error`;不包含 upload、输入大小或来源 URL。
+取消操作保留任务和已完成产物,返回后可直接使用成功文件的下载链接。底层不可中断计算和资源清理可能仍在收尾,迟到结果不会覆盖已公布的取消终态。
### files[].parse:解析统计
-成功完成后包含实际执行档位、耗时和解析器版本。档位来自结果中的 MinerU 元数据,不以创建请求的 tier 代替;响应顶层不再有 tier。
-PDF 与图片沿用多档位规则,HTML、Office 等原生文档使用 flash。同一批次可出现不同的逐文件档位。
+成功后的实际 tier 来自结果元数据,不以请求 tier 代替。PDF 和图片沿用多档位规则,HTML、Office 等原生文档使用 flash,同一批次可出现不同档位。
-| 字段 | JSON 类型 | 可为 null | 含义 |
+| 字段 | JSON 类型 | 必带 | 含义 |
|---|---|---|---|
-| `tier` | string | 否 | 实际执行档位:`flash/basic/standard/advanced`。 |
-| `duration_ms` | integer | 是 | 毫秒级文件执行耗时;当前实现包含源读取/下载、校验、解析和导出,不含等待客户端上传、准备名额及解析队列的时间。 |
-| `parser_version` | string | 是 | 执行 worker 的 MinerU 版本,不保证与 Router 的版本一致。 |
+| `tier` | string | 是 | 实际执行档位:flash/basic/standard/advanced。 |
+| `duration_ms` | integer | 否 | 已知的毫秒级耗时,包含源读取/下载、校验、解析和导出,不含等待上传、准备名额及解析队列时间。 |
+| `parser_version` | string | 否 | 已知的执行 worker 版本,不保证与 Router 版本一致。 |
### files[].upload:待上传描述
-该对象固定使用 **PUT** 上传原始文件字节;不包含 `client_file_id` 或 `upload_method`。客户端原样使用 `url` 和 `headers`,按外层文件标识关联输入。查询时仍返回当前有效的上传描述,便于断线恢复。
+固定使用 PUT 上传原始字节;对象不重复携带 file_id,也不返回 upload_method。查询仍提供当前有效的上传入口。
| 字段 | JSON 类型 | 含义 |
|---|---|---|
-| `url` | string | 上传一个文件的完整 URL;签名地址必须原样使用。 |
-| `headers` | object | 字符串到字符串的映射;上传时发送这些请求头,不假定总是固定头集合。 |
-| `expires_at` | integer | Unix 秒级截止时间,创建任务后固定,查询不续期。 |
+| `url` | string | 完整上传地址,签名 URL 原样使用。 |
+| `headers` | object | 必带的字符串请求头映射,允许为空对象。 |
+| `expires_at` | integer | 固定的 Unix 秒级截止时间,查询不续期。 |
### ErrorDetail:父任务或逐文件错误
-| 字段 | JSON 类型 | 可为 null | 含义 |
-|---|---|---|---|
-| `type` | string | 否 | 错误大类,例如 `invalid_request_error/engine_error/api_error`。 |
-| `code` | string | 是 | 机器可读错误码。 |
-| `message` | string | 否 | 人类可读错误说明,不作为客户端分支判断依据。 |
-| `param` | string | 是 | 关联参数,例如 `files.1.page_range`;无具体参数时为 `null`。 |
-
-`error=null` 不表示整个批次全部成功:父任务即使是 `partial/failed`,顶层 `error` 仍可为 `null`,错误位于具体文件的 `error` 中。
+成功快照中的 error 必带 `type/message`,有值时附带 `code/param`;空值仍省略。缺少顶层 error 不代表所有文件成功,partial/failed 的原因可能只在逐文件 error 中。
+HTTP 非成功错误 envelope 保持现有契约,见下文。
## 各接口成功响应
-以下三个示例沿用同一批两个 HTML 输入:先创建任务,再上传并完成第一个文件,最后取消仍待上传的第二个文件。
-示例来自当前响应结构,ID、地址、时间和耗时为示意值;JSON 展示全部字段,不使用省略号。
+以下完整示例使用同一批两个 HTML 输入,ID、地址、时间和耗时均为示意值。
### POST /v1/tasks:创建任务
-成功返回 **`202 Accepted` + `application/json`**,正文为 `TaskStatusResponse`。`202` 只表示任务已接单,不表示文件已经解析成功。
-初始状态通常为 `waiting-file`;URL 项在下载和校验后进入 `pending`,缓存命中项可直接进入 `pending`。需要客户端上传的文件具有非空 `upload`,其他文件的 `upload` 为 `null`。
-
-请求示例:
+返回 **202 Accepted** 和 `CreateTaskResponse`。202 表示接单,具体状态以响应为准。请求:
```json
{
"files": [
- {"file_name": "report.html", "bytes": 64},
- {"file_name": "notes.html", "bytes": 64}
+ {
+ "file_name": "report.html",
+ "bytes": 64
+ },
+ {
+ "file_name": "notes.html",
+ "bytes": 64
+ }
],
"tier": "flash",
- "output_formats": ["default"]
+ "output_formats": [
+ "default"
+ ]
}
```
-完整响应:
+创建回执:
```json
{
"task_id": "job_0123456789abcdef01234567",
"status": "waiting-file",
- "created_at": "2026-10-23T04:00:00Z",
- "started_at": null,
- "finished_at": null,
- "output_formats": [
- "default"
- ],
- "progress": {
- "completed": 0,
- "failed": 0,
- "total": 2
- },
"files": [
{
- "client_file_id": "f1",
+ "file_id": "file-111111111111111111111111",
"file_name": "report.html",
- "bytes": 64,
- "url": null,
+ "status": "waiting-file",
"upload": {
- "url": "http://127.0.0.1:8000/v1/tasks/job_0123456789abcdef01234567/uploads/f1",
+ "url": "http://127.0.0.1:8000/v1/tasks/job_0123456789abcdef01234567/uploads/file-111111111111111111111111",
"headers": {
"Content-Type": "application/octet-stream"
},
"expires_at": 1792731600
- },
- "status": "waiting-file",
- "parse": null,
- "result_url": null,
- "error": null
+ }
},
{
- "client_file_id": "f2",
+ "file_id": "file-222222222222222222222222",
"file_name": "notes.html",
- "bytes": 64,
- "url": null,
+ "status": "waiting-file",
"upload": {
- "url": "http://127.0.0.1:8000/v1/tasks/job_0123456789abcdef01234567/uploads/f2",
+ "url": "http://127.0.0.1:8000/v1/tasks/job_0123456789abcdef01234567/uploads/file-222222222222222222222222",
"headers": {
"Content-Type": "application/octet-stream"
},
"expires_at": 1792731600
- },
- "status": "waiting-file",
- "parse": null,
- "result_url": null,
- "error": null
+ }
}
- ],
- "error": null
+ ]
}
```
### GET /v1/tasks/{task_id}:查询任务
-成功返回 **`200 OK` + `application/json`**,正文始终为 `TaskStatusResponse`,包括任务仍在运行、等待上传、部分失败、全部失败或已取消时。
-以下快照中,第一个文件已完成,可立即下载;第二个文件仍等待上传,所以父任务为 `waiting-file`,`finished_at` 仍为 `null`。
+返回 **200 OK** 和 `TaskDetailResponse`,包括任务失败、取消等终态。以下第一个文件完成、第二个仍待上传,父任务仍为 waiting-file,finished_at 省略:
```json
{
@@ -264,7 +239,6 @@ PDF 与图片沿用多档位规则,HTML、Office 等原生文档使用 flash
"status": "waiting-file",
"created_at": "2026-10-23T04:00:00Z",
"started_at": "2026-10-23T04:00:01Z",
- "finished_at": null,
"output_formats": [
"default"
],
@@ -275,103 +249,85 @@ PDF 与图片沿用多档位规则,HTML、Office 等原生文档使用 flash
},
"files": [
{
- "client_file_id": "f1",
+ "file_id": "file-111111111111111111111111",
"file_name": "report.html",
"bytes": 64,
- "url": null,
- "upload": null,
"status": "completed",
"parse": {
"tier": "flash",
"duration_ms": 125,
"parser_version": "4.0.12"
},
- "result_url": "http://127.0.0.1:8000/v1/files/file-result0123456789abcdef/content",
- "error": null
+ "result_url": "http://127.0.0.1:8000/v1/files/file-111111111111111111111111/content"
},
{
- "client_file_id": "f2",
+ "file_id": "file-222222222222222222222222",
"file_name": "notes.html",
- "bytes": 64,
- "url": null,
+ "status": "waiting-file",
"upload": {
- "url": "http://127.0.0.1:8000/v1/tasks/job_0123456789abcdef01234567/uploads/f2",
+ "url": "http://127.0.0.1:8000/v1/tasks/job_0123456789abcdef01234567/uploads/file-222222222222222222222222",
"headers": {
"Content-Type": "application/octet-stream"
},
"expires_at": 1792731600
},
- "status": "waiting-file",
- "parse": null,
- "result_url": null,
- "error": null
+ "bytes": 64
}
- ],
- "error": null
+ ]
}
```
-### DELETE /v1/tasks/{task_id}:取消任务
+### POST /v1/tasks/{task_id}/cancel:取消任务
+
+无需请求体。例如:
+
+```bash
+curl --fail-with-body -X POST "$MINERU_API_URL/v1/tasks/$TASK_ID/cancel" \
+ -H "Authorization: Bearer $MINERU_API_KEY"
+```
-成功返回 **`200 OK` + `application/json`**,正文为取消后的完整 `TaskStatusResponse`,`status` 为 `canceled`,所有文件的 `upload` 均为 `null`。
-这个接口取消未完成文件,不删除 Task 或已完成的结果;返回时后台不可中断计算或资源清理可能仍在收尾。
-已经成功或失败的文件保持原状态,成功文件继续提供 `result_url`。对任意已终结的父任务再次取消,返回 `409 task_already_terminal`。
+返回 **200 OK** 和 `CancelTaskResponse`。已成功或失败的文件保留终态,其余文件转为 canceled;已终结的父任务再次取消返回 `409 task_already_terminal`。
```json
{
"task_id": "job_0123456789abcdef01234567",
"status": "canceled",
- "created_at": "2026-10-23T04:00:00Z",
- "started_at": "2026-10-23T04:00:01Z",
"finished_at": "2026-10-23T04:00:03Z",
- "output_formats": [
- "default"
- ],
- "progress": {
- "completed": 1,
- "failed": 0,
- "total": 2
- },
"files": [
{
- "client_file_id": "f1",
+ "file_id": "file-111111111111111111111111",
"file_name": "report.html",
- "bytes": 64,
- "url": null,
- "upload": null,
"status": "completed",
"parse": {
"tier": "flash",
"duration_ms": 125,
"parser_version": "4.0.12"
},
- "result_url": "http://127.0.0.1:8000/v1/files/file-result0123456789abcdef/content",
- "error": null
+ "result_url": "http://127.0.0.1:8000/v1/files/file-111111111111111111111111/content"
},
{
- "client_file_id": "f2",
+ "file_id": "file-222222222222222222222222",
"file_name": "notes.html",
- "bytes": 64,
- "url": null,
- "upload": null,
- "status": "canceled",
- "parse": null,
- "result_url": null,
- "error": null
+ "status": "canceled"
}
- ],
- "error": null
+ ]
}
```
-### PUT /v1/tasks/{task_id}/uploads/{client_file_id}:本地上传响应
+### PUT /v1/tasks/{task_id}/uploads/{file_id}:本地上传确认
-本地 API Server 和 Router 的上传成功返回 **`200 OK` + `application/json`**,正文仍为上面定义的完整 `TaskStatusResponse`。
-本次文件完成保存及校验后,`upload` 变为 `null` 并进入 `pending/running`;其他文件和已完成结果也包含在响应中。
-有效期内重复 PUT 已确认文件同样返回 `200` 和当前快照;上传链接到期后返回 `410`,不会重新读取或覆盖源字节。
+本地 API Server 和 Router 返回 **200 OK** 和 `UploadFileResponse`,不返回整份任务详情。本次文件完成保存及校验后进入 pending/running,最新详情通过 GET 获取。
+
+```json
+{
+ "task_id": "job_0123456789abcdef01234567",
+ "file_id": "file-111111111111111111111111",
+ "status": "pending"
+}
+```
-SaaS 返回的上传目标可能是独立对象存储:其成功状态码和响应体由该存储服务决定,不要求返回 Tasks JSON。
-通用客户端应接受目标服务的成功响应,随后通过 `GET /v1/tasks/{task_id}` 确认就绪情况,不把对象存储上传响应直接作为任务状态解析。
+有效期内重复 PUT 已确认文件仍返回当前文件回执,且不读取或覆盖源字节;上传窗口到期后返回 410。
+SaaS 的上传目标可能是独立对象存储:通用客户端接受成功的 2xx 响应,不要求其返回本地 PUT 回执,随后查询 Tasks 确认就绪。
## 各接口错误响应
@@ -391,13 +347,13 @@ SaaS 返回的上传目标可能是独立对象存储:其成功状态码和响
| 接口 | HTTP | 常见 code | 场景 |
|---|---|---|---|
-| POST | 400 | `invalid_request`、`page_range_invalid` | 字段、ID、页范围等非法,包括旧字段和新旧混传。 |
-| POST | 415 | `invalid_request` | 请求不是 `application/json`。 |
-| POST | 503 | `quality_tier_unavailable`、`server_shutting_down` 或模型预加载错误码 | 当前部署无法接单。 |
-| GET 详情 / DELETE / 本地 PUT | 404 | `task_not_found` | task 不存在、记录已清理或不属于当前调用方。 |
-| DELETE | 409 | `task_already_terminal` | 父任务已经成功、部分成功、失败或被取消;包括取消前刷新时刚进入终态。 |
+| POST 创建 | 400 | `invalid_request`、`page_range_invalid` | 字段、ID、页范围等非法,包括旧字段和新旧混传。 |
+| POST 创建 | 415 | `invalid_request` | 请求不是 `application/json`。 |
+| POST 创建 | 503 | `quality_tier_unavailable`、`server_shutting_down` 或模型预加载错误码 | 当前部署无法接单。 |
+| GET 详情 / POST cancel / 本地 PUT | 404 | `task_not_found` | task 不存在、记录已清理或不属于当前调用方。 |
+| POST cancel | 409 | `task_already_terminal` | 父任务已经成功、部分成功、失败或被取消;包括取消前刷新时刚进入终态。 |
| 本地 PUT | 400 | `upload_size_mismatch`、`file_hash_mismatch`、`upload_interrupted` | 上传校验失败或传输中断;未过期时可查询后重传。 |
-| 本地 PUT | 404 | `upload_not_found` | task 中不存在该 `client_file_id`。 |
+| 本地 PUT | 404 | `upload_not_found` | task 中不存在该 `file_id`。 |
| 本地 PUT | 409 | `task_already_terminal`、`file_already_terminal` | 任务已取消或文件已不接受上传。 |
| 本地 PUT | 410 | `upload_expired` | 固定上传窗口已过期。 |
| 所有受保护接口 | 401 | `invalid_api_key` | 服务启用认证,但调用方未提供有效凭据。 |
@@ -413,14 +369,14 @@ URL 输入同样先创建 JSON 任务:
```json
{
"files": [
- {"client_file_id": "remote", "file_name": "document.pdf", "url": "https://example.com/download?signature=example"},
- {"client_file_id": "local", "file_name": "other.pdf", "bytes": 12345}
+ {"file_name": "document.pdf", "url": "https://example.com/download?signature=example"},
+ {"file_name": "other.pdf", "bytes": 12345}
],
"output_formats": ["html"]
}
```
-- URL 项保持 `waiting-file` 和 `upload=null`,由服务端下载和校验;确认有效后进入 `pending`。不生成客户端上传链接,不接受 PUT,不等待其他文件上传。
+- URL 项保持 `waiting-file` 和 `upload 省略`,由服务端下载和校验;确认有效后进入 `pending`。不生成客户端上传链接,不接受 PUT,不等待其他文件上传。
- URL 保留原始签名地址,使用逻辑 `file_name` 识别类型;不要求 HEAD 或 `Content-Length`。下载后回填实际 `bytes`;请求提供的大小/hash 必须匹配,但响应不回显 hash。URL 每次下载,不用 hash 缓存跳过下载。
- 上传项 hash 命中时直接进入 `pending`,不返回上传链接;未命中或无 hash 时返回该文件的链接。上传后仍计算 hash、校验大小并对源字节去重。
- 缓存只复用源文件,不复用不匹配的解析结果;每个文件使用本次解析参数独立执行。
@@ -438,15 +394,15 @@ URL 输入同样先创建 JSON 任务:
有效期内,一个文件中断或校验失败可以从头重传,其他文件的状态不受影响。
重复 PUT 已确认文件不读取或覆盖源字节,并发请求也只提交一次解析。
-上传响应丢失时先查询:进入 `pending/running/completed` 后跳过上传;仍为 `waiting-file` 且 upload 为 null 时只轮询;有有效上传目标时才有限重试。
+上传响应丢失时先查询:进入 `pending/running/completed` 后跳过上传;仍为 `waiting-file` 且 upload 省略 时只轮询;有有效上传目标时才有限重试。
不支持单文件分块断点续传。
## 总状态与逐文件状态
状态响应只有元数据,不内联 Markdown、JSON 或结果文件字节。
-`files` 按原清单顺序返回,使用 `client_file_id` 对应输入,不依赖文件名唯一性。
+`files` 按原清单顺序返回,使用 `file_id` 对应输入,不依赖文件名唯一性。
-完整字段、类型和可空约束见 [TaskStatusResponse](#taskstatusresponse),下面说明状态聚合规则。
+各响应字段、类型及省略规则见 [响应模型](#响应模型),下面说明状态聚合规则。
Task 顶层没有 `result_url`;`files[]` 不暴露底层 `output_files`。
已完成文件可以在父任务仍为 `running/pending/waiting-file` 时下载。
@@ -484,7 +440,7 @@ DOCX 和 HTML 即使放入多格式 ZIP,也保持图片内嵌。
`default` 不包含 `model_output.json`;不生成跨输入文件的总 ZIP 或批次 `manifest.json`。
每个输入只解析一次,基于同一结果生成所选格式。全部所选格式完成并保存后才发布该文件的 `completed` 和链接。
-任一格式失败,该文件为 `failed/result_packaging_failed` 且链接为空,不提供不完整产物;其他文件继续执行。
+任一格式失败,该文件为 `failed/result_packaging_failed` 且不返回结果链接,不提供不完整产物;其他文件继续执行。
导出复用已物化素材,不重新打开源文件或修改原语义树。图片缺失时报错,不交付引用失效的 HTML 单文件。
HTML 的“单文件”保证图片内嵌,公式脚本仍沿用现有 renderer 的行为。
@@ -500,7 +456,7 @@ HTML 的“单文件”保证图片内嵌,公式脚本仍沿用现有 renderer
`scripts/http_task_example.sh` 调用同目录 Python 脚本,仅需要 Python 3.10+ 标准库。
创建请求不会自动重试;文件传输有界重试,先查询状态再处理响应丢失。
-下载使用临时文件、验证对应格式后原子保存,成功文件保存在 `RESULT_DIR/<client_file_id>/<输入文件主名>.<扩展名>`。
+下载使用临时文件、验证对应格式后原子保存,成功文件保存在 `RESULT_DIR/<file_id>/<输入文件主名>.<扩展名>`。
```bash
MINERU_API_URL=http://127.0.0.1:8000 \
diff --git a/docs/next/api/usage-limits.md b/docs/next/api/usage-limits.md
index 6360ceb4..841725a9 100644
--- a/docs/next/api/usage-limits.md
+++ b/docs/next/api/usage-limits.md
@@ -31,7 +31,7 @@ Tasks 四种输出格式不设置额外权限门槛;服务启用认证后所
|------|------|-----------|------------|
| `parse` | `POST /v1/tasks` | 5/min | 30/min |
| `chat` | `POST /v1/chat/completions`、`POST /v1/responses` | 10/min | 60/min |
-| `read` | 其他 GET/DELETE endpoint | 60/min | 300/min |
+| `read` | 其他 GET endpoint,以及 `POST /v1/tasks/{task_id}/cancel`(取消沿用控制请求配额) | 60/min | 300/min |
响应头携带当前 endpoint 类别的限流状态:
diff --git a/docs/next/sdk/api-parser.md b/docs/next/sdk/api-parser.md
index 7dfff3d0..04c7b698 100644
--- a/docs/next/sdk/api-parser.md
+++ b/docs/next/sdk/api-parser.md
@@ -18,9 +18,9 @@ print(result.markdown())
## 请求与结果
1. 校验文件及页范围,计算大小和 SHA-256,包括同机 HTTP 请求。
-2. 向 `/v1/tasks` 提交一个 `client_file_id="file"` 的 files 数组,固定请求 `output_formats=["default"]`。
+2. 向 `/v1/tasks` 提交单文件 files 数组,不指定任何文件 ID,固定请求 `output_formats=["default"]`,从创建回执记录服务端生成的 file_id,再通过首次 GET 校验详情。
3. 缓存命中不上传;未命中遍历 `files[]` 中非空的 `upload`,固定使用 PUT 向返回的链接按 headers 流式上传,并按清单大小设置 `Content-Length`。无需完成确认。
-4. 以配置的 API 基址追加 `/v1/tasks/{编码后的 task_id}` 每秒查询,保留代理路径前缀,轮询预算 3600 次;用 `client_file_id` 关联结果。
+4. 以配置的 API 基址追加 `/v1/tasks/{编码后的 task_id}`,后续每秒轮询,保留代理路径前缀,轮询预算 3600 次;用服务端生成的 `file_id` 关联结果。
5. 从该文件的 `result_url` 流式下载并校验 ZIP,读取 `middle_json.json`。
6. `include_images=True` 恢复图片素材。`ParseResult` 只持有 MiddleJson,不携带或导出 ModelJson。
@@ -32,7 +32,7 @@ HTTP 输入只有上传和 URL;SDK 的路径参数始终代表客户端文件
状态回调在创建和查询后触发,回调异常只记录日志。服务端完成表示开始下载,不等于 SDK 已经返回。
单文件成功后的 `parse` 包含实际 `tier`、`duration_ms` 和 `parser_version`。`duration_callback` 在开始下载前接收服务端单文件 `parse.duration_ms`,包含解析和导出;缺失或非法值不触发回调。
-创建请求没有幂等保证,不自动重试。上传响应丢失后先查状态:进入 pending/running/completed 后不重传;waiting-file 且 upload=null 时仅轮询;出现上传目标后才在原重试预算内发送。PUT 成功后等待确认,不因状态仍是 waiting-file 而重复上传。查询、传输和下载有界重试;任务查询和用量查询对 408/429/500/502/503/504 最多请求 3 次,支持 `Retry-After` 秒数和 HTTP 日期。单次建议等待超过 60 秒时返回原错误,不提前重试;无有效建议时使用指数退避。下载签名失效后重新查询任务。密钥仅附加到 API 同源请求,每次重定向重新判断来源。
+创建请求没有幂等保证,不自动重试。上传响应丢失后先查状态:进入 pending/running/completed 后不重传;waiting-file 且 未返回 upload 时仅轮询;出现上传目标后才在原重试预算内发送。PUT 成功后等待确认,不因状态仍是 waiting-file 而重复上传。查询、传输和下载有界重试;任务查询和用量查询对 408/429/500/502/503/504 最多请求 3 次,支持 `Retry-After` 秒数和 HTTP 日期。单次建议等待超过 60 秒时返回原错误,不提前重试;无有效建议时使用指数退避。下载签名失效后重新查询任务。密钥仅附加到 API 同源请求,每次重定向重新判断来源。
结构化业务错误保留 code/message/param。传输失败保留 `_APITransportError` 阶段及超时信息,Doclib 继续区分 `remote_timeout`、`remote_unreachable` 与业务 `parse_failed`。
diff --git a/docs/zh/usage/http_api.md b/docs/zh/usage/http_api.md
index b950e98c..6e6186a6 100644
--- a/docs/zh/usage/http_api.md
+++ b/docs/zh/usage/http_api.md
@@ -12,16 +12,16 @@ OUTPUT_FORMATS=default,docx MINERU_API_URL=http://127.0.0.1:8000 bash scripts/ht
Tasks 与 Files JSON 统一使用 `file_name`;旧字段 `manifest`、`filename` 及新旧混传返回 400。
-向 `POST /v1/tasks` 提交 `application/json`:`files` 每项包含必填逻辑 `file_name`、上传文件的 `bytes` 和可选 `client_file_id/sha256sum/page_range`。`client_file_id` 省略或为 `null` 时,先预留全部显式 ID,再按输入顺序从 `f1` 开始分配最小未占用的 `fN`;创建后上传和查询均保持不变。也可以提供 URL,此时 bytes 可省略。解析选项为 `tier/ocr_mode/page_range/output_formats`。
+向 `POST /v1/tasks` 提交 `application/json`:files 每项包含逻辑 file_name、上传文件的 bytes 和可选 sha256sum/page_range,也可提供 URL(bytes 可省略)。禁止传入 client_file_id 或 file_id;服务端生成唯一 file_id,按输入顺序返回,并在上传、查询、取消和产物下载中保持不变。解析选项为 tier/ocr_mode/page_range/output_formats。
创建返回稳定的 `task_id`;每个文件的 `upload` 为待上传描述或 `null`,包含 `url/headers/expires_at`。客户端固定使用 PUT 上传缺失文件,使用响应指定的 PUT 地址及请求头,无需 complete。每个文件就绪即独立排队,其他文件等待上传不会阻塞它。
同机也使用相同流程。SDK 总是计算 hash;已完成上传的有效缓存可以免传。并发首次请求允许重复传输,但源字节去重。缓存默认保留 24 小时、每 5 分钟扫描,正在执行及传输的引用受保护。
-上传链接固定有效一小时,查询不会续期。截止前已受理上传可继续完成。中断后先查询,进入 pending/running/completed 后跳过上传;waiting-file 且 upload=null 时只等待,有有效上传目标时才有限重试。过期文件进入 failed,错误码为 upload_expired。
+上传链接固定有效一小时,查询不会续期。截止前已受理上传可继续完成。中断后先查询,进入 pending/running/completed 后跳过上传;waiting-file 且 upload 省略 时只等待,有有效上传目标时才有限重试。过期文件进入 failed,错误码为 upload_expired。
## 状态与结果
-使用配置的 API 基址(保留代理前缀)和编码后的 task_id 构造 `GET /v1/tasks/{task_id}` 轮询。父任务状态为 `waiting-file/pending/running/completed/partial/failed/canceled`;通过 `client_file_id` 对应输入。逐文件使用同一组状态但没有 partial,不再返回 upload_status。waiting-file 包括上传、服务端下载和校验,pending 表示输入已就绪并排队等待解析。
+使用配置的 API 基址(保留代理前缀)和编码后的 task_id 构造 `GET /v1/tasks/{task_id}` 轮询。父任务状态为 `waiting-file/pending/running/completed/partial/failed/canceled`;通过创建回执中的 `file_id` 对应输入。逐文件使用同一组状态但没有 partial,不再返回 upload_status。waiting-file 包括上传、服务端下载和校验,pending 表示输入已就绪并排队等待解析。
每个成功文件在 `files[].result_url` 提供唯一下载地址,即使父任务尚未完成也可下载。顶层没有 result_url,不生成跨输入文件的总 ZIP。
| output_formats | 内容 |
@@ -33,7 +33,7 @@ Tasks 与 Files JSON 统一使用 `file_name`;旧字段 `manifest`、`filename
| 多种 | 对应文件平铺在一个 ZIP 中 |
ModelJson 仅在解析内部使用,API、SDK、CLI 和 Gradio 均不输出模型文件。`include_model_output` 已删除,提交该字段返回 400。
-`DELETE /v1/tasks/{task_id}` 取消未完成文件。任务和文件列表已移除;Files 的按 ID 元数据、结果下载和删除保留。逐文件 `parse` 在完成前为 `null`,成功后包含实际 `tier`、耗时和解析器版本;响应顶层不再有 tier。逐文件响应不回显 hash、页范围、源 file_id 或重复的 name;请求参数仍保留。
+`POST /v1/tasks/{task_id}/cancel` 取消未完成文件。任务和文件列表已移除;Files 保留按 ID 查询元数据和下载结果;不提供任务记录或产物删除接口。逐文件 `parse` 在完成前省略,成功后包含实际 `tier`、耗时和解析器版本;响应顶层不再有 tier。逐文件响应不回显 hash、页范围、底层源缓存 ID 或重复的 name;请求参数仍保留。
客户端原样使用结果链接:本地/Router 返回 Files 地址,SaaS 可返回对象存储签名地址。只为 API 同源请求附加 API Key,每次重定向重新判断;签名失效可重新查询结果链接。
@@ -44,3 +44,5 @@ ModelJson 仅在解析内部使用,API、SDK、CLI 和 Gradio 均不输出模
退出码为 0(全部成功)、2(部分成功)、1(失败或取消)、124(轮询耗尽)。已下载产物保留。
旧独立上传和 Jobs 接口已移除,客户端与服务端需协调升级,详见 [迁移说明](../../next/api/changes.md)。需要同步单文件返回时使用独立的 [file_parse 包装服务](../../next/api/file-parse.md)。
+
+POST 创建、GET 详情、POST cancel 和本地 PUT 分别返回创建回执、查询详情、逐文件取消结果和上传确认;Tasks 成功响应省略 null,但保留零值和空集合。POST cancel 取消未完成文件,成功文件的产物仍可直接下载。
diff --git a/mineru/kit/file_parse/client.py b/mineru/kit/file_parse/client.py
index 2b1abe8d..e4df7241 100644
--- a/mineru/kit/file_parse/client.py
+++ b/mineru/kit/file_parse/client.py
@@ -15,7 +15,7 @@ import httpx
from pydantic import ValidationError
from ...task_types import task_status_url
-from .models import GatewayError, Record, RemoteTask
+from .models import GatewayError, Record, RemoteCreatedTask, RemoteFile, RemoteTask
from .settings import FileParseSettings, origin
CHUNK_BYTES = 1024 * 1024
@@ -122,13 +122,15 @@ class TaskClient:
def _snapshot(self, body: bytes, expected: RemoteTask | None, formats: list[str]) -> RemoteTask:
"""校验任务 ID、单文件映射和输出格式,拒绝不匹配的任务响应。"""
try:
- task = RemoteTask.model_validate_json(body)
+ task = RemoteTask.model_validate({**json.loads(body), "details_loaded": True})
if expected is not None and task.task_id != expected.task_id:
raise ValueError("Task identity changed")
if list(dict.fromkeys(task.output_formats)) != formats:
raise ValueError("Task output formats changed")
if expected is not None and (
- task.files[0].file_name != expected.files[0].file_name or task.files[0].bytes != expected.files[0].bytes
+ task.files[0].file_id != expected.files[0].file_id
+ or task.files[0].file_name != expected.files[0].file_name
+ or task.files[0].bytes != expected.files[0].bytes
):
raise ValueError("Task input identity changed")
for item in task.files:
@@ -137,9 +139,29 @@ class TaskClient:
if task.files[0].result_url:
task.files[0].result_url = self.resolve(task.files[0].result_url)
return task
- except (ValidationError, ValueError) as exc:
+ except (ValidationError, ValueError, TypeError) as exc:
raise GatewayError("upstream_protocol_error", "Upstream returned inconsistent task metadata") from exc
+ def _created_snapshot(self, body: bytes, request: dict[str, Any]) -> RemoteTask:
+ """用创建回执和本地请求构造恢复上下文,查询详情之前即可安全持久化 ID。"""
+ try:
+ created = RemoteCreatedTask.model_validate_json(body)
+ item = created.files[0]
+ source = request["files"][0]
+ if item.file_name != source["file_name"]:
+ raise ValueError("Created task input identity changed")
+ if item.upload is not None:
+ item.upload.url = self.resolve(item.upload.url)
+ return RemoteTask(
+ task_id=created.task_id,
+ status=created.status,
+ files=[RemoteFile(**item.model_dump(), bytes=source["bytes"])],
+ output_formats=request["output_formats"],
+ details_loaded=False,
+ )
+ except (ValidationError, ValueError) as exc:
+ raise GatewayError("upstream_protocol_error", "Upstream returned inconsistent creation metadata") from exc
+
async def _json_request(
self,
method: str,
@@ -159,6 +181,9 @@ class TaskClient:
if method == "POST" and (response.status_code >= 500 or response.status_code == 408):
raise GatewayError("submission_unknown", "Task creation outcome is unknown; not resubmitting")
raise error
+ if method == "POST":
+ assert payload is not None
+ return self._created_snapshot(body, payload)
return self._snapshot(body, expected, formats)
except (httpx.HTTPError, GatewayError) as exc:
error = (
@@ -182,7 +207,6 @@ class TaskClient:
**options,
"files": [
{
- "client_file_id": "file",
"file_name": record.filename,
"bytes": record.size,
"sha256sum": record.sha256sum,
diff --git a/mineru/kit/file_parse/models.py b/mineru/kit/file_parse/models.py
index 8ec8a9e4..1524f1a1 100644
--- a/mineru/kit/file_parse/models.py
+++ b/mineru/kit/file_parse/models.py
@@ -71,39 +71,55 @@ class UploadLink(BaseModel):
class RemoteFile(BaseModel):
"""仅消费共同 Tasks 契约,不依赖本地 Files 或 Job 实现。"""
- client_file_id: str
+ file_id: str = Field(min_length=1)
file_name: str
bytes: int
status: FileStatus
- upload: UploadLink | None
+ upload: UploadLink | None = None
result_url: str | None = None
error: dict[str, Any] | None = None
class RemoteTask(BaseModel):
- """校验单文件任务的身份和产物契约,允许上游添加其他元数据。"""
+ """保存客户端私有上下文,标记是否已经取得查询详情以支持创建后立即恢复。"""
task_id: str = Field(min_length=1)
status: TaskStatus
files: list[RemoteFile] = Field(min_length=1, max_length=1)
output_formats: list[TaskOutputFormat] = Field(min_length=1)
+ details_loaded: bool = True
@model_validator(mode="after")
def validate_file(self) -> RemoteTask:
"""确保返回的文件和链接仍对应本次唯一清单项。"""
item = self.files[0]
task_status_url("", self.task_id)
- if item.client_file_id != "file":
- raise ValueError("Unexpected client_file_id")
if item.upload is not None and item.status != "waiting-file":
raise ValueError("Only waiting-file accepts uploads")
- if item.status == "completed" and not item.result_url:
+ if self.details_loaded and item.status == "completed" and not item.result_url:
raise ValueError("Completed file has no result_url")
if item.status != "completed" and item.result_url is not None:
raise ValueError("Unfinished file has a result_url")
return self
+class RemoteCreatedFile(BaseModel):
+ """只消费创建回执中的文件身份、状态与上传描述。"""
+
+ file_id: str = Field(min_length=1)
+ file_name: str
+ status: FileStatus
+ upload: UploadLink | None = None
+
+
+class RemoteCreatedTask(BaseModel):
+ """单独校验创建回执,不要求它包含大小、输出格式或结果链接。"""
+
+ task_id: str = Field(min_length=1)
+ status: TaskStatus
+ files: list[RemoteCreatedFile] = Field(min_length=1, max_length=1)
+
+
@dataclass
class Record:
"""保存恢复所需的最小状态;密钥仅来自启动配置,不写入记录。"""
@@ -125,6 +141,11 @@ class Record:
"""读取已校验远端快照,空值表示尚未确认创建结果。"""
return RemoteTask.model_validate(self.remote) if self.remote is not None else None
+ @property
+ def needs_details(self) -> bool:
+ """创建已报告完成但首次查询失败时,重启或重复请求仍需补取结果详情。"""
+ return self.status == "completed" and self.remote is not None and self.remote.get("details_loaded") is False
+
def to_json(self) -> str:
"""把完整记录序列化为 SQLite 单行快照。"""
return json.dumps(asdict(self), ensure_ascii=False)
@@ -137,4 +158,4 @@ def fingerprint(filename: str, size: int, sha256sum: str, options: ParseOptions)
return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True).encode()).hexdigest()
-__all__ = ["GatewayError", "ParseOptions", "Record", "RemoteTask", "TERMINAL", "UploadLink", "fingerprint"]
+__all__ = ["GatewayError", "ParseOptions", "Record", "RemoteCreatedTask", "RemoteTask", "TERMINAL", "UploadLink", "fingerprint"]
diff --git a/mineru/kit/file_parse/service.py b/mineru/kit/file_parse/service.py
index 53b564eb..1aaa8268 100644
--- a/mineru/kit/file_parse/service.py
+++ b/mineru/kit/file_parse/service.py
@@ -46,7 +46,7 @@ class FileParseService:
await self._remember_error(
record, GatewayError("submission_unknown", "Task creation outcome is unknown; not resubmitting")
)
- elif record.status not in TERMINAL:
+ elif record.status not in TERMINAL or record.needs_details:
self._prepare_in_background(record)
await self.collect()
self._monitor = asyncio.create_task(self._monitor_records(), name="file-parse-monitor")
@@ -94,7 +94,7 @@ class FileParseService:
source.unlink(missing_ok=True)
if existing.fingerprint != identity:
raise GatewayError("request_id_conflict", "request_id already identifies a different request", 409)
- if existing.status not in TERMINAL:
+ if existing.status not in TERMINAL or existing.needs_details:
self._prepare_in_background(existing)
return existing
record = Record(request_id, filename, size, sha256sum, options.model_dump(), str(source), identity)
@@ -179,6 +179,8 @@ class FileParseService:
await self.store.save(record)
task = await self.client.create(record)
await self._apply(record, task)
+ # 创建身份已持久化;首次查询失败也只能恢复此任务,不能重新提交。
+ task = await self.refresh(record)
else:
task = await self.refresh(record)
if task.files[0].status == "waiting-file":
@@ -219,7 +221,7 @@ class FileParseService:
record
for record in self.records.values()
if record.remote is not None
- and record.status not in TERMINAL
+ and (record.status not in TERMINAL or record.needs_details)
and (record.request_id not in self.preparations or self.preparations[record.request_id].done())
]
try:
diff --git a/mineru/kit/file_parse/settings.py b/mineru/kit/file_parse/settings.py
index 0903a353..004e34ea 100644
--- a/mineru/kit/file_parse/settings.py
+++ b/mineru/kit/file_parse/settings.py
@@ -56,7 +56,7 @@ class FileParseSettings:
@property
def namespace(self) -> str:
"""按新任务协议、上游和认证隔离记录,保留但不加载旧协议状态。"""
- return "tasks-v4-" + hashlib.sha256(f"{self.api_url}\0{self.api_key or ''}".encode()).hexdigest()
+ return "tasks-v5-" + hashlib.sha256(f"{self.api_url}\0{self.api_key or ''}".encode()).hexdigest()
__all__ = ["FileParseSettings", "origin"]
diff --git a/mineru/kit/router/app.py b/mineru/kit/router/app.py
index 88e8bd2a..a6ae0b80 100644
--- a/mineru/kit/router/app.py
+++ b/mineru/kit/router/app.py
@@ -377,21 +377,6 @@ def create_app(
request=request,
)
- @application.delete("/v1/files/{file_id}")
- async def delete_file(file_id: str, request: Request) -> Response:
- """删除所属 worker 的 file,并在成功后清除 Router 映射。"""
- owner_scope = _caller_scope(request)
- route = _route_or_404(registry, "file", file_id, owner_scope)
- worker = pool.get(route.worker_id)
- upstream = await request_upstream(pool, worker, "DELETE", f"/v1/files/{route.upstream_id}", request=request)
- result = _successful_json(upstream)
- if isinstance(result, Response):
- return result
- registry.remove("file", file_id)
- source_store.delete_file(file_id)
- result["id"] = file_id
- return JSONResponse(result, status_code=upstream.status_code)
-
@application.get("/v1/usage")
async def usage(request: Request) -> dict[str, Any]:
"""返回当前 Router 进程聚合的 V1 usage。"""
diff --git a/mineru/kit/router/proxy.py b/mineru/kit/router/proxy.py
index a5fee2ef..90ae0b93 100644
--- a/mineru/kit/router/proxy.py
+++ b/mineru/kit/router/proxy.py
@@ -187,6 +187,8 @@ def rewrite_file_payload(
worker: WorkerState,
registry: ResourceRegistry,
owner_scope: str,
+ *,
+ public_id: str | None = None,
) -> dict[str, Any]:
"""注册 upstream file 并把响应中的 file ID 改成 Router 公共 ID。"""
rewritten = copy.deepcopy(payload)
@@ -198,6 +200,7 @@ def rewrite_file_payload(
owner_scope=owner_scope,
worker_id=worker.worker_id,
upstream_id=upstream_id,
+ public_id=public_id,
)
if "id" in rewritten:
rewritten["id"] = route.public_id
diff --git a/mineru/kit/router/resources.py b/mineru/kit/router/resources.py
index 76e9133b..0eba9507 100644
--- a/mineru/kit/router/resources.py
+++ b/mineru/kit/router/resources.py
@@ -248,6 +248,36 @@ class ResourceRegistry:
}
self._by_upstream: dict[tuple[ResourceKind, str, str, str], ResourceRoute] = {}
self._retired_usage: dict[str, dict[str, int]] = {}
+ self._allocated_file_ids: set[str] = set()
+ self._reserved_file_ids: set[str] = set()
+ self._task_file_ids: set[str] = set()
+
+ def reserve_file_id(self, *, task_owned: bool = True) -> str:
+ """在本层预留公共文件 ID,完成前不登记可访问的 Files 路由。"""
+ while True:
+ file_id = self._new_public_id("file")
+ if file_id not in self._allocated_file_ids and file_id not in self._by_public["file"]:
+ self._allocated_file_ids.add(file_id)
+ self._reserved_file_ids.add(file_id)
+ if task_owned:
+ self._task_file_ids.add(file_id)
+ return file_id
+
+ def forget_file_id(self, file_id: str) -> None:
+ """任务记录过期后回收占用索引,仍存在的公开资源保持唯一性。"""
+ self._task_file_ids.discard(file_id)
+ self._reserved_file_ids.discard(file_id)
+ if file_id not in self._by_public["file"]:
+ self._allocated_file_ids.discard(file_id)
+
+ def is_file_reserved(self, file_id: str) -> bool:
+ """区分仍可发布的产物预留与已经取消、删除或过期的资源。"""
+ return file_id in self._reserved_file_ids
+
+ def discard_file_id(self, file_id: str) -> None:
+ """撤销失败或取消文件的预留与结果映射,保留已用 ID 防止迟到结果复活。"""
+ self._reserved_file_ids.discard(file_id)
+ self.remove("file", file_id)
def register(
self,
@@ -263,11 +293,22 @@ class ResourceRegistry:
upstream_key = (kind, owner_scope, worker_id, upstream_id)
existing = self._by_upstream.get(upstream_key)
if existing is not None:
+ if public_id is not None and public_id != existing.public_id:
+ raise ValueError("Upstream resource is already bound to another public ID")
if metadata is not None:
existing.metadata = dict(metadata)
return existing
- resolved_public_id = public_id or self._new_public_id(kind)
+ resolved_public_id = public_id or (
+ self.reserve_file_id(task_owned=False) if kind == "file" else self._new_public_id(kind)
+ )
+ if resolved_public_id in self._by_public[kind]:
+ raise ValueError("Public resource ID is already occupied")
+ if kind == "file":
+ if resolved_public_id in self._allocated_file_ids and resolved_public_id not in self._reserved_file_ids:
+ raise ValueError("File reservation has already been consumed or discarded")
+ self._allocated_file_ids.add(resolved_public_id)
+ self._reserved_file_ids.discard(resolved_public_id)
route = ResourceRoute(
kind=kind,
public_id=resolved_public_id,
@@ -380,6 +421,8 @@ class ResourceRegistry:
def remove(self, kind: ResourceKind, public_id: str) -> ResourceRoute | None:
"""删除公共资源及其反向索引,并返回被删除的记录。"""
route = self._by_public[kind].pop(public_id, None)
+ if kind == "file" and public_id not in self._task_file_ids and public_id not in self._reserved_file_ids:
+ self._allocated_file_ids.discard(public_id)
if route is not None:
if kind == "job":
totals = self._retired_usage.setdefault(route.owner_scope, {"jobs_created": 0, "files_processed": 0})
diff --git a/mineru/kit/router/tasks.py b/mineru/kit/router/tasks.py
index 6cbe0409..b5a670b2 100644
--- a/mineru/kit/router/tasks.py
+++ b/mineru/kit/router/tasks.py
@@ -22,10 +22,14 @@ from ...filetypes import is_flash_only_parse_extension
from ...parser.api_server import ApiServerError, ErrorDetail, _JobInputMetadata, _raise_api_error
from ...parser.task_api import (
TERMINAL_TASK_STATUSES,
+ CreateTaskResponse,
+ CancelTaskResponse,
TaskExecution,
+ TaskFileInput,
TaskFileItem,
- TaskStatusResponse,
+ TaskDetailResponse,
TaskUpload,
+ UploadFileResponse,
UploadTaskOptions,
file_chunks,
resolve_task_tier,
@@ -166,7 +170,7 @@ async def read_task_execution(
if response.status_code == 404 or worker.generation != generation or route.metadata.get("upstream_lost"):
return _lost_execution(route, pool)
try:
- payload = TaskStatusResponse.model_validate(_checked_json(response)).model_dump()
+ payload = TaskDetailResponse.model_validate(_checked_json(response)).model_dump()
except ValidationError as exc:
_raise_api_error(502, error_type="api_error", code="invalid_upstream_response", message=str(exc))
if payload["task_id"] != route.upstream_id:
@@ -174,6 +178,10 @@ async def read_task_execution(
result_file_id: str | None = None
if len(payload["files"]) != 1:
_raise_api_error(502, error_type="api_error", code="invalid_upstream_response", message="Expected one task file")
+ upstream_file_id = payload["files"][0]["file_id"]
+ public_file_id = route.metadata["file_ids"].get(upstream_file_id)
+ if public_file_id is None or payload["files"][0]["file_name"] != route.metadata["file_names"].get(upstream_file_id):
+ _raise_api_error(502, error_type="api_error", code="invalid_upstream_response", message="Worker file identity changed")
if payload["files"][0]["status"] == "completed":
result_url = payload["files"][0].get("result_url")
if not isinstance(result_url, str):
@@ -182,9 +190,13 @@ async def read_task_execution(
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 result File URL")
- upstream_file_id = unquote(parts[2])
+ if unquote(parts[2]) != upstream_file_id:
+ _raise_api_error(502, error_type="api_error", code="invalid_upstream_response", message="Result file ID changed")
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):
+ if existing is None and not registry.is_file_reserved(public_file_id):
+ # 取消、删除或过期的结果不因迟到响应重新登记;任务保持已发布的终态。
+ result_file_id = public_file_id
+ elif existing is None or not isinstance(existing.metadata.get("payload"), dict):
metadata = _checked_json(
await _worker_request(
pool,
@@ -200,8 +212,12 @@ async def read_task_execution(
_raise_api_error(
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"]
+ result_file_id = rewrite_file_payload(metadata, worker, registry, route.owner_scope, public_id=public_file_id)["id"]
else:
+ if existing.public_id != public_file_id:
+ _raise_api_error(
+ 502, error_type="api_error", code="invalid_upstream_response", message="Public file ID changed"
+ )
result_file_id = existing.public_id
result_route = registry.find("file", result_file_id)
if result_route is not None:
@@ -240,6 +256,18 @@ class RouterTaskBackend:
"""每个输入文件拥有独立暂存引用和 worker 调度上下文。"""
return RouterTaskBackend(self.request, self.owner_scope, self.finalize)
+ def reserve_file_id(self) -> str:
+ """每层 Router 独立预留公共 ID,通过内部映射关联下游生成的标识。"""
+ return self.registry.reserve_file_id()
+
+ def discard_file_id(self, file_id: str) -> None:
+ """取消本层预留或尚未发布的结果映射,不触碰共享源缓存。"""
+ self.registry.discard_file_id(file_id)
+
+ def forget_file_id(self, file_id: str) -> None:
+ """父任务记录过期后回收本层 ID 索引,不依赖 worker 路由仍然存在。"""
+ self.registry.forget_file_id(file_id)
+
async def release_result(self, task_id: str, finished: float) -> None:
"""父任务完成后记录公开保留期限,后台续租直到该期限再释放 worker。"""
# 私有源缓存独立于 worker 路由,即使 worker 已丢失也必须开始回收倒计时。
@@ -259,7 +287,7 @@ class RouterTaskBackend:
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, inputs: list[TaskFileItem]) -> None:
+ async def validate(self, options: UploadTaskOptions, inputs: list[TaskFileInput]) -> None:
"""能力预检不推进轮询游标,也不为尚未上传的任务预占 worker。"""
tiers = self.pool.available_tiers()
options.tier = resolve_task_tier(options, inputs, tiers, select_default_quality_tier(tiers))
@@ -322,7 +350,7 @@ class RouterTaskBackend:
self._pins.close()
async def _wait_for_uploads_ready(
- self, worker: WorkerState, upstream_id: str, generation: int, inputs: list[TaskFileItem]
+ self, worker: WorkerState, upstream_id: str, generation: int, inputs: list[TaskFileItem], file_ids: dict[str, str]
) -> dict[str, Any]:
"""只等待上传确认,不要求下游暴露源 File 或完成内部引用交接。"""
while True:
@@ -335,12 +363,15 @@ class RouterTaskBackend:
headers={"x-mineru-task-lease-seconds": "120"},
)
require_worker_generation(worker, generation)
- ready = TaskStatusResponse.model_validate(_checked_json(response)).model_dump()
+ ready = TaskDetailResponse.model_validate(_checked_json(response)).model_dump()
if ready["task_id"] != upstream_id or len(ready["files"]) != len(inputs):
_raise_api_error(
502, error_type="api_error", code="invalid_upstream_response", message="Worker inputs are not ready"
)
- if any(item["client_file_id"] != source.client_file_id for item, source in zip(ready["files"], inputs)):
+ if any(
+ file_ids.get(item["file_id"]) != source.file_id or item["file_name"] != source.file_name
+ for item, source in zip(ready["files"], inputs)
+ ):
_raise_api_error(
502, error_type="api_error", code="invalid_upstream_response", message="Worker input order changed"
)
@@ -380,9 +411,9 @@ class RouterTaskBackend:
transferred = False
try:
worker_inputs = [
- item.model_dump(exclude_none=True)
+ item.model_dump(exclude_none=True, exclude={"file_id"})
if item.url is not None
- else {**item.model_dump(exclude_none=True), "sha256sum": uploads[index].sha256sum}
+ else {**item.model_dump(exclude_none=True, exclude={"file_id"}), "sha256sum": uploads[index].sha256sum}
for index, item in enumerate(inputs)
]
response = await _worker_request(
@@ -400,7 +431,7 @@ class RouterTaskBackend:
headers={"x-mineru-task-lease-seconds": "120"},
)
require_worker_generation(worker, reservation.generation)
- payload = TaskStatusResponse.model_validate(_checked_json(response)).model_dump()
+ payload = CreateTaskResponse.model_validate(_checked_json(response)).model_dump()
upstream_id = payload["task_id"]
route = self.registry.register(
"job",
@@ -411,14 +442,18 @@ class RouterTaskBackend:
)
authorization = self.request.headers.get("authorization")
route.metadata.update(
+ file_ids={item["file_id"]: source.file_id for item, source in zip(payload["files"], inputs)},
+ file_names={item["file_id"]: source.file_name for item, source in zip(payload["files"], inputs)},
task_result_held=True,
active_counted=True,
reservation=reservation,
upstream_headers={"authorization": authorization} if authorization else {},
payload={"job_id": task_id, "status": "pending", "files": []},
)
- if len(payload["files"]) != len(inputs) or any(
- item["client_file_id"] != source.client_file_id for item, source in zip(payload["files"], inputs)
+ if (
+ len(payload["files"]) != len(inputs)
+ or len(route.metadata["file_ids"]) != len(inputs)
+ or any(item["file_name"] != source.file_name for item, source in zip(payload["files"], inputs))
):
_raise_api_error(
502, error_type="api_error", code="invalid_upstream_response", message="Worker input order changed"
@@ -432,7 +467,7 @@ class RouterTaskBackend:
502, error_type="api_error", code="invalid_upstream_response", message="Unexpected worker upload"
)
path = _worker_path(worker, link["url"])
- expected_path = f"/v1/tasks/{quote(upstream_id, safe='')}/uploads/{quote(item['client_file_id'], safe='')}"
+ expected_path = f"/v1/tasks/{quote(upstream_id, safe='')}/uploads/{quote(item['file_id'], safe='')}"
if path != expected_path:
_raise_api_error(
502, error_type="api_error", code="invalid_upstream_response", message="Invalid worker upload path"
@@ -450,10 +485,19 @@ class RouterTaskBackend:
"x-mineru-task-lease-seconds": "120",
},
)
- if response.status_code >= 400:
- _checked_json(response)
+ try:
+ acknowledged = UploadFileResponse.model_validate(_checked_json(response))
+ except ValidationError as exc:
+ _raise_api_error(502, error_type="api_error", code="invalid_upstream_response", message=str(exc))
+ if acknowledged.task_id != upstream_id or acknowledged.file_id != item["file_id"]:
+ _raise_api_error(
+ 502,
+ error_type="api_error",
+ code="invalid_upstream_response",
+ message="Upload acknowledgement ID changed",
+ )
require_worker_generation(worker, reservation.generation)
- await self._wait_for_uploads_ready(worker, upstream_id, reservation.generation, inputs)
+ await self._wait_for_uploads_ready(worker, upstream_id, reservation.generation, inputs, route.metadata["file_ids"])
result = await self.get(task_id)
self._task_sources.extend(self._prepared_sources)
self._prepared_sources.clear()
@@ -475,7 +519,9 @@ class RouterTaskBackend:
async def _cancel_remote(self, worker: WorkerState, upstream_id: str) -> None:
"""尽力取消已经创建的 worker 任务,清理失败不覆盖最初的提交错误。"""
try:
- await _worker_request(self.pool, worker, "DELETE", f"/v1/tasks/{upstream_id}", request=self.request)
+ await _worker_request(
+ self.pool, worker, "POST", f"/v1/tasks/{quote(upstream_id, safe='')}/cancel", request=self.request
+ )
except Exception:
# worker 已不可达或被替换时,原始错误及任务保留策略仍负责后续诊断。
return
@@ -505,9 +551,22 @@ class RouterTaskBackend:
release_job_load(route, self.pool)
return
worker = self.pool.get(route.worker_id)
- response = await _worker_request(self.pool, worker, "DELETE", f"/v1/tasks/{route.upstream_id}", request=self.request)
+ response = await _worker_request(
+ self.pool, worker, "POST", f"/v1/tasks/{quote(route.upstream_id, safe='')}/cancel", request=self.request
+ )
if response.status_code not in {404, 409}:
- _checked_json(response)
+ try:
+ canceled = CancelTaskResponse.model_validate(_checked_json(response))
+ except ValidationError as exc:
+ _raise_api_error(502, error_type="api_error", code="invalid_upstream_response", message=str(exc))
+ if (
+ canceled.task_id != route.upstream_id
+ or [item.file_id for item in canceled.files] != list(route.metadata["file_ids"])
+ or any(item.file_name != route.metadata["file_names"].get(item.file_id) for item in canceled.files)
+ ):
+ _raise_api_error(
+ 502, error_type="api_error", code="invalid_upstream_response", message="Cancellation file identity changed"
+ )
execution = await self.get(task_id)
if execution.job["status"] in TERMINAL_TASK_STATUSES:
release_job_load(route, self.pool)
diff --git a/mineru/parser/api_client.py b/mineru/parser/api_client.py
index e781b389..a26f88b4 100644
--- a/mineru/parser/api_client.py
+++ b/mineru/parser/api_client.py
@@ -172,7 +172,6 @@ class MinerUApiParser(DocumentParser):
payload: dict[str, Any] = {
"files": [
{
- "client_file_id": "file",
"file_name": path.name,
"bytes": path.stat().st_size,
"sha256sum": _sha256_file(path),
@@ -187,8 +186,8 @@ class MinerUApiParser(DocumentParser):
payload["ocr_mode"] = self.ocr_mode
return payload
- def _snapshot(self, response: httpx.Response, expected: dict[str, Any] | None = None) -> dict[str, Any]:
- """校验稳定任务身份、唯一文件映射和产物选项,不依赖文件名或数组位置。"""
+ def _task_identity(self, response: httpx.Response, expected: dict[str, Any] | None = None) -> dict[str, Any]:
+ """校验创建和查询共有的身份字段,只把服务端确认的文件 ID 用于后续请求。"""
task = self._check(response)
files = task.get("files")
if (
@@ -196,35 +195,44 @@ class MinerUApiParser(DocumentParser):
or not task["task_id"]
or not isinstance(task.get("status"), str)
or task.get("status") not in _JOB_STATUSES
- or task.get("output_formats") != ["default"]
or not isinstance(files, list)
or len(files) != 1
or not isinstance(files[0], dict)
- or files[0].get("client_file_id") != "file"
+ or not isinstance(files[0].get("file_id"), str)
+ or not files[0]["file_id"]
+ or not isinstance(files[0].get("file_name"), str)
or (expected is not None and task["task_id"] != expected["task_id"])
):
raise _V1APIError("invalid_response", "Inconsistent Tasks response")
item = files[0]
- if item.get("status") not in (
- "waiting-file",
- "pending",
- "running",
- "completed",
- "failed",
- "canceled",
- ):
+ if item.get("status") not in ("waiting-file", "pending", "running", "completed", "failed", "canceled"):
raise _V1APIError("invalid_response", "Invalid task file state")
- if "upload" not in item or (item["upload"] is not None and not isinstance(item["upload"], dict)):
+ link = item.get("upload")
+ if link is not None and (not isinstance(link, dict) or item["status"] != "waiting-file"):
raise _V1APIError("invalid_response", "Invalid task upload descriptor")
- if item["upload"] is not None and item["status"] != "waiting-file":
- raise _V1APIError("invalid_response", "Only waiting-file accepts uploads")
- if expected is not None and any(item.get(key) != expected["files"][0].get(key) for key in ("file_name", "bytes")):
+ if expected is not None and any(item.get(key) != expected["files"][0].get(key) for key in ("file_id", "file_name")):
raise _V1APIError("invalid_response", "Task input identity changed")
try:
task_status_url(self._base_url, task["task_id"])
except ValueError as exc:
raise _V1APIError("invalid_response", str(exc)) from exc
- if files[0].get("status") == "completed" and not isinstance(files[0].get("result_url"), str):
+ return task
+
+ def _created_task(self, response: httpx.Response, request: dict[str, Any]) -> dict[str, Any]:
+ """创建回执无需携带详情;本地请求大小保留为首次 GET 的身份校验依据。"""
+ task = self._task_identity(response)
+ item = task["files"][0]
+ if item["file_name"] != request["files"][0]["file_name"]:
+ raise _V1APIError("invalid_response", "Created task input identity changed")
+ return {**task, "files": [{**item, "bytes": request["files"][0]["bytes"]}]}
+
+ def _snapshot(self, response: httpx.Response, expected: dict[str, Any]) -> dict[str, Any]:
+ """GET 独立校验完整详情,缺失可选字段不沿用上一快照的旧值。"""
+ task = self._task_identity(response, expected)
+ item = task["files"][0]
+ if task.get("output_formats") != ["default"] or item.get("bytes") != expected["files"][0]["bytes"]:
+ raise _V1APIError("invalid_response", "Task input size or output formats changed")
+ if item["status"] == "completed" and not isinstance(item.get("result_url"), str):
raise _V1APIError("invalid_response", "Completed file is missing result_url")
return task
@@ -248,8 +256,12 @@ class MinerUApiParser(DocumentParser):
headers=self._headers(),
json_body=payload,
)
- task = self._snapshot(response)
+ task = self._created_task(response, payload)
_notify_job_status(task, status_callback)
+ created_status = task["status"]
+ task = self._query(cli, task)
+ if task["status"] != created_status:
+ _notify_job_status(task, status_callback)
upload_state = _UploadState()
task = self._upload_input(
cli, task, file_path, status_callback, size=payload["files"][0]["bytes"], upload_state=upload_state
@@ -298,10 +310,10 @@ class MinerUApiParser(DocumentParser):
"""只有明确待上传时才发 PUT,上传成功及等待确认均不消耗重复传输。"""
if task["files"][0]["status"] != "waiting-file":
upload_state.accepted = True
- if upload_state.accepted or task["files"][0]["upload"] is None:
+ if upload_state.accepted or task["files"][0].get("upload") is None:
return task
while upload_state.attempts < _TRANSPORT_MAX_ATTEMPTS:
- link = task["files"][0]["upload"]
+ link = task["files"][0].get("upload")
if link is None:
return task
url = self._resolve(link["url"])
@@ -320,7 +332,7 @@ class MinerUApiParser(DocumentParser):
if task["files"][0]["status"] != "waiting-file":
upload_state.accepted = True
return task
- if task["files"][0]["upload"] is None:
+ if task["files"][0].get("upload") is None:
return task
if isinstance(exc, _V1APIError) and response.status_code not in {408, 429, 500, 502, 503, 504}:
raise
@@ -408,8 +420,12 @@ class MinerUApiParser(DocumentParser):
headers=self._headers(),
json_body=payload,
)
- task = self._snapshot(response)
+ task = self._created_task(response, payload)
_notify_job_status(task, status_callback)
+ created_status = task["status"]
+ task = await self._async_query(cli, task)
+ if task["status"] != created_status:
+ _notify_job_status(task, status_callback)
upload_state = _UploadState()
task = await self._async_upload_input(
cli, task, file_path, status_callback, size=payload["files"][0]["bytes"], upload_state=upload_state
@@ -458,10 +474,10 @@ class MinerUApiParser(DocumentParser):
"""只有明确待上传时才发 PUT,上传成功及等待确认均不消耗重复传输。"""
if task["files"][0]["status"] != "waiting-file":
upload_state.accepted = True
- if upload_state.accepted or task["files"][0]["upload"] is None:
+ if upload_state.accepted or task["files"][0].get("upload") is None:
return task
while upload_state.attempts < _TRANSPORT_MAX_ATTEMPTS:
- link = task["files"][0]["upload"]
+ link = task["files"][0].get("upload")
if link is None:
return task
url = self._resolve(link["url"])
@@ -482,7 +498,7 @@ class MinerUApiParser(DocumentParser):
if task["files"][0]["status"] != "waiting-file":
upload_state.accepted = True
return task
- if task["files"][0]["upload"] is None:
+ if task["files"][0].get("upload") is None:
return task
if isinstance(exc, _V1APIError) and response.status_code not in {408, 429, 500, 502, 503, 504}:
raise
diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.py
index 98edd4eb..a5ab21d8 100644
--- a/mineru/parser/api_server.py
+++ b/mineru/parser/api_server.py
@@ -313,13 +313,6 @@ class FileObjectModel(BaseModel):
sha256sum: str | None = None
-class FileDeletionResponse(BaseModel):
- model_config = _PYDANTIC_CONFIG
- id: str
- object: Literal["file"] = "file"
- deleted: bool = True
-
-
# ── Job sources ──────────────────────────────────────────────────────
@@ -450,6 +443,9 @@ class FileStore:
self._blobs = root / "blobs"
self._blobs.mkdir(parents=True, exist_ok=True)
self._files: dict[str, _FileRecord] = {}
+ self._allocated_file_ids: set[str] = set()
+ self._reserved_output_ids: set[str] = set()
+ self._task_file_ids: set[str] = set()
def claim_directory(self) -> None:
"""服务启动时独占上传目录,避免多个进程的内存元数据互相误删。"""
@@ -521,6 +517,8 @@ class FileStore:
for file_id, rec in tuple(self._files.items()):
if rec.expires_at is not None and rec.expires_at <= now:
self._files.pop(file_id)
+ if file_id not in self._task_file_ids:
+ self._allocated_file_ids.discard(file_id)
referenced = {rec.sha256sum for rec in self._files.values()} | set(self._pins)
for prefix in self._blobs.iterdir():
if prefix.is_symlink() or not prefix.is_dir() or not re.fullmatch(r"[0-9a-f]{2}", prefix.name):
@@ -543,8 +541,56 @@ class FileStore:
@staticmethod
def _new_file_id() -> str:
+ """生成不携带存储位置或内容信息的随机文件标识。"""
return "file-" + secrets.token_hex(12)
+ def _allocate_file_id(self) -> str:
+ """检查源文件、产物和仍被任务持有的 ID,避免覆盖活跃资源。"""
+ with self._lock:
+ while True:
+ file_id = self._new_file_id()
+ if file_id not in self._allocated_file_ids and file_id not in self._files:
+ self._allocated_file_ids.add(file_id)
+ return file_id
+
+ def reserve_file_id(self, *, task_owned: bool = True) -> str:
+ """只预留公共产物 ID,完成前不建立可查询的 Files 对象。"""
+ with self._lock:
+ file_id = self._allocate_file_id()
+ self._reserved_output_ids.add(file_id)
+ if task_owned:
+ self._task_file_ids.add(file_id)
+ return file_id
+
+ def forget_file_id(self, file_id: str) -> None:
+ """任务记录过期后回收 ID 索引,仍存在的 Files 资源继续阻止占用。"""
+ with self._lock:
+ self._task_file_ids.discard(file_id)
+ self._reserved_output_ids.discard(file_id)
+ if file_id not in self._files:
+ self._allocated_file_ids.discard(file_id)
+
+ def discard_file_id(self, file_id: str) -> None:
+ """取消未发布的产物及其预留,迟到写出不得重新注册该 ID。"""
+ with self._lock:
+ self._reserved_output_ids.discard(file_id)
+ record = self._files.get(file_id)
+ if record is not None and record.purpose == "parse_output":
+ self._files.pop(file_id)
+
+ def _store_path(self, path: pathlib.Path, sha256sum: str) -> pathlib.Path:
+ """在持有存储锁时物化共享字节,源文件和产物复用相同的原子写入。"""
+ target = self._blob_abs(sha256sum)
+ if not target.is_file():
+ target.parent.mkdir(parents=True, exist_ok=True)
+ temporary = target.with_name(target.name + "." + secrets.token_hex(8))
+ try:
+ shutil.copyfile(path, temporary)
+ os.replace(temporary, target)
+ finally:
+ temporary.unlink(missing_ok=True)
+ return target
+
# ── blob helpers ─────────────────────────────────────────────────
@staticmethod
@@ -576,17 +622,20 @@ class FileStore:
) -> str:
"""从已校验的暂存文件原子注册源字节及独立的文件名视图。"""
with self._lock:
- target = self._blob_abs(sha256sum)
- if not target.is_file():
- target.parent.mkdir(parents=True, exist_ok=True)
- temporary = target.with_name(target.name + "." + secrets.token_hex(8))
- try:
- shutil.copyfile(path, temporary)
- os.replace(temporary, target)
- finally:
- temporary.unlink(missing_ok=True)
+ file_id = file_id or self._allocate_file_id()
+ existing = self._files.get(file_id)
+ if (
+ file_id in self._task_file_ids
+ or file_id in self._reserved_output_ids
+ or (
+ existing is not None
+ and (existing.purpose != "parse" or existing.filename != filename or existing.sha256sum != sha256sum)
+ )
+ ):
+ raise ValueError("File ID already belongs to another resource")
+ self._allocated_file_ids.add(file_id)
+ target = self._store_path(path, sha256sum)
now = int(time.time())
- file_id = file_id or self._new_file_id()
self._files[file_id] = _FileRecord(
id=file_id,
filename=filename,
@@ -607,19 +656,28 @@ class FileStore:
if record is not None:
record.expires_at = expires_at
- def create_file_for_output_path(self, filename: str, path: pathlib.Path, *, job_id: str) -> str:
- """从已完成的文件流式登记产物,避免批量 ZIP 再次整体载入内存。"""
+ def create_file_for_output_path(self, filename: str, path: pathlib.Path, *, job_id: str, file_id: str | None = None) -> str:
+ """把完整产物原子登记到预分配 ID,已取消或已消费的预留不能再次写入。"""
hasher = hashlib.sha256()
with path.open("rb") as source:
while chunk := source.read(1024 * 1024):
hasher.update(chunk)
sha = hasher.hexdigest()
with self._lock:
- file_id = self.register_source_file(filename, path, sha)
- record = self._files[file_id]
- record.purpose = "parse_output"
- record.job_id = job_id
- record.expires_at = None
+ file_id = file_id or self.reserve_file_id(task_owned=False)
+ if file_id not in self._reserved_output_ids or file_id in self._files:
+ raise ValueError("Output file ID is not reserved or has already been published")
+ target = self._store_path(path, sha)
+ self._files[file_id] = _FileRecord(
+ id=file_id,
+ filename=filename,
+ bytes=target.stat().st_size,
+ created_at=int(time.time()),
+ purpose="parse_output",
+ sha256sum=sha,
+ job_id=job_id,
+ )
+ self._reserved_output_ids.remove(file_id)
pins = self._job_output_pins.setdefault(job_id, set())
if sha not in pins:
pins.add(sha)
@@ -657,7 +715,7 @@ class FileStore:
sha = sha256hex or hashlib.sha256(data).hexdigest()
self.store_blob(data, sha256hex=sha)
now = int(time.time())
- file_id = self._new_file_id()
+ file_id = self._allocate_file_id()
self._files[file_id] = _FileRecord(
id=file_id,
filename=filename,
@@ -728,6 +786,8 @@ class FileStore:
message=f"File {file_id} not found",
)
del self._files[file_id]
+ if file_id not in self._task_file_ids:
+ self._allocated_file_ids.discard(file_id)
# ── defaults → app state ─────────────────────────────────────────
@@ -799,6 +859,7 @@ class _JobInputSpec:
filename: str
bytes: int | None = None
sha256sum: str | None = None
+ result_file_id: str | None = None
@dataclass(frozen=True)
@@ -836,6 +897,15 @@ class _JobRecord:
self.progress = TaskProgress()
+def _discard_unfinished_outputs(rec: _JobRecord) -> None:
+ """执行取消或失败时立即撤销未完成产物,防止后台线程晚于终态发布文件。"""
+ if rec.file_store is None:
+ return
+ for index, spec in rec.input_specs.items():
+ if spec.result_file_id is not None and rec.files[index].status != "completed":
+ rec.file_store.discard_file_id(spec.result_file_id)
+
+
class JobStore:
def __init__(self, concurrency: int = 1, retention_seconds: int = 86400) -> None:
self.retention_seconds = retention_seconds
@@ -867,6 +937,7 @@ class JobStore:
file.status = "failed"
file.error = ErrorDetail(type="engine_error", code="engine_dead", message=message)
rec.progress.failed = rec.progress.total - rec.progress.completed
+ _discard_unfinished_outputs(rec)
if task is not current and not task.cancelling():
task.cancel()
@@ -933,6 +1004,7 @@ class JobStore:
logger.error("Parse job task failed: %s", rec.id, exc_info=(type(error), error, error.__traceback__))
if rec.status != "canceled":
rec.status = "failed"
+ _discard_unfinished_outputs(rec)
self._record_usage(rec)
self._completion_events[rec.id].set()
@@ -1065,6 +1137,7 @@ class JobStore:
message=f"Job is {rec.status}",
)
rec.status = "canceled"
+ _discard_unfinished_outputs(rec)
task = self._tasks.get(job_id)
if task is not None and not task.done():
task.cancel()
@@ -1396,7 +1469,11 @@ async def _run_job(
pathlib.Path(fr.name).stem + artifact.suffix,
artifact,
job_id=rec.id,
+ file_id=rec.input_specs[i].result_file_id if i in rec.input_specs else None,
)
+ if rec.status in {"canceled", "failed"}:
+ file_store.discard_file_id(rec.task_result_file_id)
+ break
except Exception as exc:
raise MineruError("result_packaging_failed", str(exc)) from exc
@@ -1448,11 +1525,11 @@ _router = APIRouter(prefix="/v1")
# OpenAPI tag metadata: drives the group order and descriptions on /docs.
_OPENAPI_TAGS: list[dict[str, str]] = [
- {"name": "Tasks", "description": "Form submissions, per-file uploads and asynchronous ZIP download links."},
+ {"name": "Tasks", "description": "JSON task creation, per-file uploads, details and cancellation receipts."},
{"name": "Health", "description": "Liveness and server readiness."},
{"name": "Tiers", "description": "Parsing tiers and runtime capability advertised by this server."},
{"name": "Models", "description": "VLM models available for parsing."},
- {"name": "Files", "description": "Inspect uploaded files and fetch parsed content."},
+ {"name": "Files", "description": "Inspect saved files and download completed parsing artifacts."},
{"name": "Usage", "description": "Remote service quota and usage reporting."},
]
@@ -1646,22 +1723,6 @@ async def get_file_content(
return _OutputFileResponse(store, file_id)
-@_router.delete(
- "/files/{file_id}",
- response_model=FileDeletionResponse,
- status_code=status.HTTP_200_OK,
- responses={**_ERR_404},
- tags=["Files"],
-)
-async def delete_file(
- file_id: str = Path(description="File ID"),
- store: FileStore = Depends(_get_store),
-) -> FileDeletionResponse:
- """Delete a file from the current tenant view."""
- store.delete_file(file_id)
- return FileDeletionResponse(id=file_id, deleted=True)
-
-
# ── 私有解析执行 ─────────────────────────────────────────────────────
diff --git a/mineru/parser/task_api.py b/mineru/parser/task_api.py
index bc54f77d..f90d1b80 100644
--- a/mineru/parser/task_api.py
+++ b/mineru/parser/task_api.py
@@ -52,10 +52,9 @@ logger = logging.getLogger(__name__)
class TaskFileInput(BaseModel):
- """声明上传或 URL 输入,客户端可以省略任务内文件标识。"""
+ """仅声明输入,文件标识由服务端分配,不接受任何客户端 ID。"""
model_config = ConfigDict(extra="forbid")
- client_file_id: str | None = Field(default=None, pattern=r"^[A-Za-z0-9_-]{1,64}$")
file_name: str = Field(min_length=1, max_length=1024)
bytes: int | None = Field(default=None, gt=0, strict=True)
url: str | None = None
@@ -76,7 +75,7 @@ class TaskFileInput(BaseModel):
class TaskFileItem(TaskFileInput):
"""接单前补全文件标识,内部执行和状态响应只消费完整文件条目。"""
- client_file_id: str = Field(pattern=r"^[A-Za-z0-9_-]{1,64}$")
+ file_id: str
class UploadTaskOptions(BaseModel):
@@ -103,28 +102,52 @@ class TaskUploadLink(BaseModel):
expires_at: int
-class TaskFileStatus(BaseModel):
+class CreatedTaskFile(BaseModel):
+ """创建回执只提供输入映射、当前状态和可执行的上传动作。"""
+
+ file_id: str = Field(min_length=1)
+ file_name: str
+ status: TaskFileState
+ upload: TaskUploadLink | None = None
+
+ @model_validator(mode="after")
+ def validate_upload_action(self) -> CreatedTaskFile:
+ """创建回执的上传动作只能属于仍在等待文件的条目。"""
+ if self.upload is not None and self.status != "waiting-file":
+ raise ValueError("Only waiting-file accepts uploads")
+ return self
+
+
+class CreateTaskResponse(BaseModel):
+ """创建回执独立于查询详情,后续详情扩展不会进入创建响应。"""
+
+ task_id: str
+ status: TaskStatus
+ files: list[CreatedTaskFile]
+
+
+class TaskFileDetail(BaseModel):
"""用统一状态描述文件准备和解析,上传对象仅表示客户端当前可执行的动作。"""
- client_file_id: str = Field(pattern=r"^[A-Za-z0-9_-]{1,64}$")
+ file_id: str = Field(min_length=1)
file_name: str
- bytes: int | None
- url: str | None
- upload: TaskUploadLink | None
+ bytes: int | None = None
+ url: str | None = None
+ upload: TaskUploadLink | None = None
status: TaskFileState
parse: FileParseInfo | None = None
result_url: str | None = None
error: ErrorDetail | None = None
@model_validator(mode="after")
- def validate_upload_action(self) -> TaskFileStatus:
+ def validate_upload_action(self) -> TaskFileDetail:
"""只有等待客户端文件的条目才能提供上传目标,服务端准备阶段可以为空。"""
if self.upload is not None and (self.status != "waiting-file" or self.url is not None):
raise ValueError("Only waiting-file without a URL source accepts uploads")
return self
-class TaskStatusResponse(BaseModel):
+class TaskDetailResponse(BaseModel):
"""任务状态只携带元数据;每个成功文件提供自己的下载链接。"""
task_id: str
@@ -134,10 +157,38 @@ class TaskStatusResponse(BaseModel):
finished_at: str | None = None
output_formats: list[TaskOutputFormat]
progress: TaskProgress
- files: list[TaskFileStatus]
+ files: list[TaskFileDetail]
error: ErrorDetail | None = None
+class CanceledTaskFile(BaseModel):
+ """取消回执保留每个文件的终态、可下载产物和失败原因。"""
+
+ file_id: str = Field(min_length=1)
+ file_name: str
+ status: Literal["completed", "failed", "canceled"]
+ parse: FileParseInfo | None = None
+ result_url: str | None = None
+ error: ErrorDetail | None = None
+
+
+class CancelTaskResponse(BaseModel):
+ """取消回执只描述本次取消后的确定终态,不携带上传或查询扩展字段。"""
+
+ task_id: str
+ status: Literal["canceled"]
+ finished_at: str
+ files: list[CanceledTaskFile]
+
+
+class UploadFileResponse(BaseModel):
+ """确认一次文件上传,仅返回对应文件的身份和当前状态。"""
+
+ task_id: str
+ file_id: str = Field(min_length=1)
+ status: TaskFileState
+
+
@dataclass(frozen=True)
class TaskUpload:
"""保存已校验的源字节位置,文件名视图独立于内容去重路径。"""
@@ -165,6 +216,18 @@ class TaskBackend(Protocol):
owner_scope: str
+ def reserve_file_id(self) -> str:
+ """在本层 Files 命名空间内预留唯一产物 ID。"""
+ ...
+
+ def discard_file_id(self, file_id: str) -> None:
+ """撤销失败或取消文件的预留及尚未发布的结果。"""
+ ...
+
+ def forget_file_id(self, file_id: str) -> None:
+ """任务回收后释放预留索引,不删除仍有效的产物资源。"""
+ ...
+
def fork(self) -> TaskBackend:
"""为每个文件创建独立的引用和执行上下文。"""
...
@@ -173,7 +236,7 @@ class TaskBackend(Protocol):
"""父任务收尾后解除子结果租约,并开始正常保留期。"""
...
- async def validate(self, options: UploadTaskOptions, inputs: list[TaskFileItem]) -> None:
+ async def validate(self, options: UploadTaskOptions, inputs: list[TaskFileInput]) -> None:
"""在接单之前校验部署能力,不能预占解析名额。"""
...
@@ -215,7 +278,7 @@ def _invalid(message: str, *, code: str = "invalid_request", status_code: int =
)
-def resolve_task_tier(options: UploadTaskOptions, inputs: list[TaskFileItem], tiers: set[Tier], default: Tier | None) -> Tier:
+def resolve_task_tier(options: UploadTaskOptions, inputs: list[TaskFileInput], tiers: set[Tier], default: Tier | None) -> Tier:
"""按现有轻量格式回退规则解析 tier,不触发 worker 选择或模型执行。"""
lightweight = [is_flash_only_parse_extension(item.file_name) for item in inputs]
if any(lightweight) and "flash" not in tiers:
@@ -272,31 +335,21 @@ async def _save_upload(
raise
-def _normalize_task_files(inputs: list[TaskFileInput]) -> list[TaskFileItem]:
- """先预留全部显式标识,再按输入顺序给缺省项分配最小可用的 fN。"""
- used_ids: set[str] = set()
- for index, item in enumerate(inputs):
- if item.client_file_id is None:
- continue
- if item.client_file_id in used_ids:
- _invalid("client_file_id must be unique within a task", param=f"files.{index}.client_file_id")
- used_ids.add(item.client_file_id)
-
+def _normalize_task_files(inputs: list[TaskFileInput], backend: TaskBackend) -> list[TaskFileItem]:
+ """按请求顺序为每个输入预留公共产物 ID,失败时撤销已分配的预留。"""
normalized: list[TaskFileItem] = []
- next_id = 1
- for item in inputs:
- client_file_id = item.client_file_id
- if client_file_id is None:
- while f"f{next_id}" in used_ids:
- next_id += 1
- client_file_id = f"f{next_id}"
- used_ids.add(client_file_id)
- next_id += 1
- normalized.append(TaskFileItem.model_validate({**item.model_dump(), "client_file_id": client_file_id}))
- return normalized
-
-
-async def _read_submission(request: Request) -> tuple[UploadTaskOptions, list[TaskFileItem]]:
+ try:
+ for item in inputs:
+ normalized.append(TaskFileItem(**item.model_dump(), file_id=backend.reserve_file_id()))
+ return normalized
+ except BaseException:
+ for item in normalized:
+ backend.discard_file_id(item.file_id)
+ backend.forget_file_id(item.file_id)
+ raise
+
+
+async def _read_submission(request: Request) -> tuple[UploadTaskOptions, list[TaskFileInput]]:
"""只读取 JSON 清单,严格拒绝表单、直传字节和 URL 查询参数。"""
if request.query_params:
_invalid("POST parameters must be supplied in the JSON body, not the URL")
@@ -305,7 +358,7 @@ async def _read_submission(request: Request) -> tuple[UploadTaskOptions, list[Ta
_invalid("Use application/json", status_code=415)
try:
body = CreateTaskRequest.model_validate(await request.json())
- inputs = _normalize_task_files(body.files)
+ inputs = body.files
options = UploadTaskOptions.model_validate(body.model_dump(exclude={"files"}))
options.page_range = normalize_page_range_input(options.page_range)
options.output_formats = list(dict.fromkeys(options.output_formats))
@@ -347,6 +400,7 @@ class _TaskFileRecord:
"""每个文件独立拥有准备引用、执行 ID 和一次性提交句柄。"""
backend: TaskBackend
+ file_id: str
execution_id: str = field(default_factory=JobStore._new_job_id)
status: TaskFileState = "waiting-file"
upload: TaskUpload | None = None
@@ -453,6 +507,8 @@ class TaskStore:
and record.operation.done()
):
self._records.pop(task_id, None)
+ for item in record.inputs:
+ record.backend.forget_file_id(item.file_id)
shutil.rmtree(record.directory, ignore_errors=True)
def lookup(self, task_id: str, owner_scope: str) -> _TaskRecord:
@@ -473,12 +529,13 @@ class TaskStore:
record.changed.set()
async def create(
- self, backend: TaskBackend, options: UploadTaskOptions, inputs: list[TaskFileItem], *, lease_seconds: int = 0
+ self, backend: TaskBackend, options: UploadTaskOptions, inputs: list[TaskFileInput], *, lease_seconds: int = 0
) -> _TaskRecord:
"""先完整校验清单并固定缓存,再为各个就绪文件独立提交执行。"""
if self._closing:
_invalid("Server is shutting down", status_code=503, code="server_shutting_down")
await backend.validate(options, inputs)
+ inputs = _normalize_task_files(inputs, backend)
task_id = JobStore._new_job_id()
record = _TaskRecord(
task_id,
@@ -487,7 +544,7 @@ class TaskStore:
inputs,
self._root / task_id,
int(time.time()) + TASK_UPLOAD_TTL,
- [_TaskFileRecord(backend.fork()) for _ in inputs],
+ [_TaskFileRecord(backend.fork(), file_id=item.file_id) for item in inputs],
)
self.update_lease(record, lease_seconds)
try:
@@ -507,6 +564,9 @@ class TaskStore:
record.operation = asyncio.create_task(self._monitor(record), name=f"mineru-task-{task_id}")
return record
except BaseException:
+ for item in inputs:
+ backend.discard_file_id(item.file_id)
+ backend.forget_file_id(item.file_id)
for file in record.file_states:
file.backend.release_uploads(rollback=True)
raise
@@ -567,6 +627,7 @@ class TaskStore:
continue
if file.status not in TERMINAL_TASK_STATUSES:
file.status = "failed"
+ file.backend.discard_file_id(file.file_id)
file.error = (
result.error
if isinstance(result, ApiServerError)
@@ -581,6 +642,7 @@ class TaskStore:
file.lease_refresh_at = time.monotonic() + 30
except ApiServerError as exc:
file.status = "failed"
+ file.backend.discard_file_id(file.file_id)
file.error = exc.error
if file.operation is not None:
file.operation.cancel()
@@ -599,6 +661,8 @@ class TaskStore:
if file.status not in TERMINAL_TASK_STATUSES:
await file.finished.wait()
except asyncio.CancelledError:
+ if file.status != "completed":
+ file.backend.discard_file_id(file.file_id)
try:
await drain_future(asyncio.create_task(file.backend.cancel(file.execution_id)))
except Exception:
@@ -613,6 +677,8 @@ class TaskStore:
if isinstance(exc, ApiServerError)
else ErrorDetail(type="api_error", code="task_submission_failed", message=str(exc))
)
+ if file.status != "completed":
+ file.backend.discard_file_id(file.file_id)
try:
await file.backend.cancel(file.execution_id)
except Exception:
@@ -634,6 +700,9 @@ class TaskStore:
operations = [file.operation for file in record.file_states if file.operation is not None]
if operations:
await asyncio.gather(*operations, return_exceptions=True)
+ for item, file in zip(record.inputs, record.file_states):
+ if file.status != "completed":
+ file.backend.discard_file_id(item.file_id)
while any(file.upload_active for file in record.file_states) or record.lease_expires_at > time.time():
record.changed.clear()
await self._wait_for_change(record)
@@ -655,11 +724,11 @@ class TaskStore:
except asyncio.TimeoutError:
pass
- async def upload(self, record: _TaskRecord, client_file_id: str, request: Request) -> bool:
+ async def upload(self, record: _TaskRecord, file_id: str, request: Request) -> bool:
"""在接收主体前检查固定期限,已受理流不因父任务状态变化中止。"""
- index = next((i for i, item in enumerate(record.inputs) if item.client_file_id == client_file_id), None)
+ index = next((i for i, item in enumerate(record.inputs) if item.file_id == file_id), None)
if index is None:
- _invalid("Unknown client_file_id", status_code=404, code="upload_not_found")
+ _invalid("Unknown file_id", status_code=404, code="upload_not_found")
expected = record.inputs[index]
if expected.url is not None:
_invalid("URL inputs do not accept uploads")
@@ -724,9 +793,10 @@ class TaskStore:
record.finished_at = JobStore._now()
record.finished_epoch = time.time()
record.changed.set()
- for file in record.file_states:
+ for item, file in zip(record.inputs, record.file_states):
if file.status not in TERMINAL_TASK_STATUSES:
file.status = "canceled"
+ file.backend.discard_file_id(item.file_id)
if file.operation is not None:
file.operation.cancel()
if wait and record.operation is not None:
@@ -755,67 +825,102 @@ def _url(request: Request, path: str) -> str:
return str(request.base_url).rstrip("/") + path
-def task_payload(record: _TaskRecord, request: Request) -> dict[str, Any]:
- """逐文件合并上传与执行元数据,成功文件立即给出独立下载链接。"""
- files: list[dict[str, Any]] = []
- starts: list[str] = []
- for item, state in zip(record.inputs, record.file_states):
- file: dict[str, Any] = {
- "client_file_id": item.client_file_id,
- "file_name": item.file_name,
- "bytes": item.bytes,
- "url": item.url,
- "status": state.status,
- "upload": None,
- "parse": None,
- "result_url": None,
- "error": None,
- }
- if state.execution is not None:
- job = state.execution.job
- results = job.get("files") or []
- if results:
- file["error"] = results[0].get("error")
- if state.status == "completed":
- file["parse"] = results[0].get("parse")
- if job.get("started_at"):
- starts.append(job["started_at"])
- if (metadata := state.execution.input_metadata.get(0)) is not None:
- file["bytes"] = metadata.bytes
- 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()
- if (
- item.url is None
- and state.upload is None
- and not state.upload_active
- and state.status == "waiting-file"
- and record.status != "canceled"
- and record.expires_at > time.time()
- ):
- file["upload"] = {
- "url": _url(request, f"/v1/tasks/{record.id}/uploads/{quote(item.client_file_id, safe='')}"),
- "headers": {"Content-Type": "application/octet-stream"},
- "expires_at": record.expires_at,
- }
- files.append(file)
- payload = {
- "task_id": record.id,
- "status": record.status,
- "created_at": record.created_at,
- "started_at": min(starts) if starts else None,
- "finished_at": record.finished_at,
- "output_formats": record.options.output_formats,
- "progress": {
- "completed": sum(file.status == "completed" for file in record.file_states),
- "failed": sum(file.status == "failed" for file in record.file_states),
- "total": len(files),
- },
- "files": files,
- "error": record.error.model_dump() if record.error else None,
+def _upload_descriptor(record: _TaskRecord, index: int, request: Request) -> TaskUploadLink | None:
+ """上传描述仅表示当前可执行的动作,不将服务端准备误判为文件就绪。"""
+ item, state = record.inputs[index], record.file_states[index]
+ if (
+ item.url is None
+ and state.upload is None
+ and not state.upload_active
+ and state.status == "waiting-file"
+ and record.status != "canceled"
+ and record.expires_at > time.time()
+ ):
+ return TaskUploadLink(
+ url=_url(request, f"/v1/tasks/{record.id}/uploads/{quote(item.file_id, safe='')}"),
+ headers={"Content-Type": "application/octet-stream"},
+ expires_at=record.expires_at,
+ )
+ return None
+
+
+def _file_payload(record: _TaskRecord, index: int, request: Request) -> dict[str, Any]:
+ """从内部执行记录提取文件信息,各响应模型显式限定自身公开字段。"""
+ item, state = record.inputs[index], record.file_states[index]
+ payload: dict[str, Any] = {
+ "file_id": item.file_id,
+ "file_name": item.file_name,
+ "bytes": item.bytes,
+ "url": item.url,
+ "status": state.status,
+ "upload": _upload_descriptor(record, index, request),
}
- return TaskStatusResponse.model_validate(payload).model_dump()
+ if state.execution is not None:
+ results = state.execution.job.get("files") or []
+ if results:
+ payload["error"] = results[0].get("error")
+ if state.status == "completed":
+ payload["parse"] = results[0].get("parse")
+ if (metadata := state.execution.input_metadata.get(0)) is not None:
+ payload["bytes"] = metadata.bytes
+ if state.status == "completed" and state.execution.result_file_id:
+ if state.execution.result_file_id != item.file_id:
+ raise ValueError("Result file identity differs from the reserved task file ID")
+ payload["result_url"] = _url(request, f"/v1/files/{quote(item.file_id, safe='')}/content")
+ if state.error is not None:
+ payload["error"] = state.error
+ return payload
+
+
+def create_task_payload(record: _TaskRecord, request: Request) -> dict[str, Any]:
+ """创建响应只确认服务端文件标识和上传入口,不依赖 GET 详情模型。"""
+ return CreateTaskResponse(
+ task_id=record.id,
+ status=record.status,
+ files=[
+ CreatedTaskFile(
+ file_id=item.file_id,
+ file_name=item.file_name,
+ status=state.status,
+ upload=_upload_descriptor(record, index, request),
+ )
+ for index, (item, state) in enumerate(zip(record.inputs, record.file_states))
+ ],
+ ).model_dump(exclude_none=True)
+
+
+def task_payload(record: _TaskRecord, request: Request) -> dict[str, Any]:
+ """查询返回当前完整详情,递归省略空值且保留进度中的零。"""
+ starts = [
+ state.execution.job["started_at"]
+ for state in record.file_states
+ if state.execution is not None and state.execution.job.get("started_at")
+ ]
+ return TaskDetailResponse(
+ task_id=record.id,
+ status=record.status,
+ created_at=record.created_at,
+ started_at=min(starts) if starts else None,
+ finished_at=record.finished_at,
+ output_formats=record.options.output_formats,
+ progress=TaskProgress(
+ completed=sum(state.status == "completed" for state in record.file_states),
+ failed=sum(state.status == "failed" for state in record.file_states),
+ total=len(record.inputs),
+ ),
+ files=[TaskFileDetail.model_validate(_file_payload(record, index, request)) for index in range(len(record.inputs))],
+ error=record.error,
+ ).model_dump(exclude_none=True)
+
+
+def cancel_task_payload(record: _TaskRecord, request: Request) -> dict[str, Any]:
+ """取消响应保留全部逐文件终态和成功产物,不携带上传或其他详情字段。"""
+ return CancelTaskResponse(
+ task_id=record.id,
+ status=record.status,
+ finished_at=record.finished_at,
+ files=[CanceledTaskFile.model_validate(_file_payload(record, index, request)) for index in range(len(record.inputs))],
+ ).model_dump(exclude_none=True)
def _request_schema() -> dict[str, Any]:
@@ -840,7 +945,7 @@ def build_task_router(factory: Callable[[Request], TaskBackend]) -> APIRouter:
"""两类部署使用同一任务协议,下载交给已有 Files 入口。"""
router = APIRouter(prefix="/v1", tags=["Tasks"])
- @router.post("/tasks", status_code=202, response_model=TaskStatusResponse, openapi_extra=_request_schema())
+ @router.post("/tasks", status_code=202, response_model=CreateTaskResponse, openapi_extra=_request_schema())
async def create_task(request: Request) -> Response:
"""先验证 JSON 再建立稳定任务 ID,HTTP 结束后逐文件工作独立继续。"""
backend = factory(request)
@@ -851,9 +956,9 @@ def build_task_router(factory: Callable[[Request], TaskBackend]) -> APIRouter:
except BaseException:
backend.release_uploads(rollback=True)
raise
- return JSONResponse(task_payload(record, request), status_code=202)
+ return JSONResponse(create_task_payload(record, request), status_code=202)
- @router.get("/tasks/{task_id}", response_model=TaskStatusResponse)
+ @router.get("/tasks/{task_id}", response_model=TaskDetailResponse)
async def get_task(task_id: str, request: Request) -> Response:
"""读取逐文件状态与结果地址,上传链接截止时间保持不变。"""
store: TaskStore = request.app.state.task_store
@@ -863,8 +968,8 @@ def build_task_router(factory: Callable[[Request], TaskBackend]) -> APIRouter:
return JSONResponse(task_payload(record, request))
@router.put(
- "/tasks/{task_id}/uploads/{client_file_id}",
- response_model=TaskStatusResponse,
+ "/tasks/{task_id}/uploads/{file_id}",
+ response_model=UploadFileResponse,
openapi_extra={
"requestBody": {
"required": True,
@@ -872,28 +977,32 @@ def build_task_router(factory: Callable[[Request], TaskBackend]) -> APIRouter:
}
},
)
- async def upload_task_file(task_id: str, client_file_id: str, request: Request) -> Response:
+ async def upload_task_file(task_id: str, 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)
+ skipped = await store.upload(record, file_id, request)
# 大文件转传可超过租约长度;受理完成时续租,保护紧接着发布的结果。
store.update_lease(record, lease_seconds)
return JSONResponse(
- task_payload(record, request),
+ UploadFileResponse(
+ task_id=record.id,
+ file_id=file_id,
+ status=next(state.status for item, state in zip(record.inputs, record.file_states) if item.file_id == file_id),
+ ).model_dump(),
headers={"Connection": "close"} if skipped and request.scope.get("http_version") == "1.1" else None,
)
- @router.delete("/tasks/{task_id}", response_model=TaskStatusResponse)
+ @router.post("/tasks/{task_id}/cancel", response_model=CancelTaskResponse)
async def cancel_task(task_id: str, request: Request) -> Response:
"""统一取消等待上传与正在执行的任务,不重建后台作业。"""
store: TaskStore = request.app.state.task_store
record = store.lookup(task_id, factory(request).owner_scope)
await store.refresh(record)
await store.cancel(record, wait=False)
- return JSONResponse(task_payload(record, request))
+ return JSONResponse(cancel_task_payload(record, request))
return router
@@ -914,11 +1023,23 @@ class ApiTaskBackend:
"""为单个文件隔离源字节引用,其他文件提交不释放本文件资源。"""
return ApiTaskBackend(self.request)
+ def reserve_file_id(self) -> str:
+ """在 API Server 的 Files 存储中预留统一的公共产物 ID。"""
+ return self.files.reserve_file_id()
+
+ def discard_file_id(self, file_id: str) -> None:
+ """取消或失败时使结果预留失效,不影响共享的源文件缓存。"""
+ self.files.discard_file_id(file_id)
+
+ def forget_file_id(self, file_id: str) -> None:
+ """任务记录过期后释放 ID 预留索引,Files 自身仍遵循原保留期。"""
+ self.files.forget_file_id(file_id)
+
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, inputs: list[TaskFileItem]) -> None:
+ async def validate(self, options: UploadTaskOptions, inputs: list[TaskFileInput]) -> None:
"""复用引擎就绪状态,提前校验显式 tier 与轻量格式能力。"""
_require_model_preload_ready(self.request)
if self.jobs._closing:
@@ -945,7 +1066,7 @@ class ApiTaskBackend:
async def retain_upload(self, upload: TaskUpload) -> TaskUpload:
"""立即按内容去重并登记独立文件视图,后续文件失败不丢弃已成功上传项。"""
- file_id = self.files._new_file_id()
+ file_id = self.files._allocate_file_id()
self._owned_files.append(file_id)
await run_sync(
self.files.register_source_file, upload.filename, upload.path, upload.sha256sum, file_id, keep_alive=True
@@ -962,6 +1083,7 @@ class ApiTaskBackend:
for file_id in self._owned_files:
if file_id in self.files._files:
self.files.delete_file(file_id)
+ self.files.forget_file_id(file_id)
else:
self.files.finalize_source_views(self._owned_files)
self._owned_files.clear()
@@ -997,7 +1119,10 @@ class ApiTaskBackend:
self.files,
self.jobs,
job_id=task_id,
- input_specs={index: _JobInputSpec(item.file_name, item.bytes, item.sha256sum) for index, item in enumerate(inputs)},
+ input_specs={
+ index: _JobInputSpec(item.file_name, item.bytes, item.sha256sum, result_file_id=item.file_id)
+ for index, item in enumerate(inputs)
+ },
)
return await self.get(task_id)
@@ -1028,7 +1153,10 @@ __all__ = [
"TaskExecution",
"TaskFileItem",
"TaskFileInput",
- "TaskStatusResponse",
+ "CreateTaskResponse",
+ "TaskDetailResponse",
+ "CancelTaskResponse",
+ "UploadFileResponse",
"TaskStore",
"TaskUpload",
"UploadTaskOptions",
diff --git a/scripts/http_task_example.py b/scripts/http_task_example.py
index 9b9601b9..7aab3665 100644
--- a/scripts/http_task_example.py
+++ b/scripts/http_task_example.py
@@ -7,6 +7,7 @@ import hashlib
import http.client
import json
import os
+import re
import socket
import sys
import tempfile
@@ -40,16 +41,15 @@ class ClientError(RuntimeError):
@dataclass(frozen=True)
class InputFile:
- """固定文件顺序和客户端标识,恢复任务时仍按同一份清单对应文件。"""
+ """固定原始文件顺序,创建或恢复时绑定服务端返回的文件标识。"""
path: Path
- client_file_id: str
size: int
sha256sum: str | None
def task_file(self) -> dict[str, Any]:
"""生成 JSON 清单条目;关闭 hash 时完全省略该可选字段。"""
- item: dict[str, Any] = {"client_file_id": self.client_file_id, "file_name": self.path.name, "bytes": self.size}
+ item: dict[str, Any] = {"file_name": self.path.name, "bytes": self.size}
if self.sha256sum is not None:
item["sha256sum"] = self.sha256sum
return item
@@ -102,7 +102,7 @@ class TaskClient:
raise ClientError("MINERU_API_URL must not contain a query or fragment")
self.key = os.environ.get("MINERU_API_KEY", "")
self.files = files
- self.by_id = {item.client_file_id: item for item in files}
+ self.by_id: dict[str, InputFile] = {}
self.connect_timeout = _integer("CONNECT_TIMEOUT", 10)
self.timeout = _integer("REQUEST_TIMEOUT", 600)
self.max_polls = _integer("MAX_POLLS", 300, minimum=0)
@@ -232,10 +232,10 @@ class TaskClient:
raise ClientError("Task response is not valid JSON") from exc
if not isinstance(payload, dict):
raise ClientError("Task response must be a JSON object")
- return self.validate_task(payload)
+ return self.validate_creation(payload) if method == "POST" else self.validate_task(payload)
- def validate_task(self, payload: dict[str, Any]) -> dict[str, Any]:
- """校验任务身份和文件映射,恢复请求不能误把文件上传给另一项。"""
+ def _validate_file_map(self, payload: dict[str, Any], *, details: bool) -> dict[str, Any]:
+ """按原始顺序绑定服务端 ID,此后校验同一映射,避免同名输入被错误关联。"""
task_id = payload.get("task_id")
if (
not isinstance(task_id, str)
@@ -249,20 +249,21 @@ class TaskClient:
files = payload.get("files")
if not isinstance(files, list) or len(files) != len(self.files):
raise ClientError("Task file count does not match local inputs")
- seen: set[str] = set()
- for item in files:
+ bindings: dict[str, InputFile] = {}
+ for item, local in zip(files, self.files):
if not isinstance(item, dict):
raise ClientError("Invalid task file entry")
- client_id = item.get("client_file_id")
- if not isinstance(client_id, str) or client_id not in self.by_id or client_id in seen:
- raise ClientError("Invalid or duplicate client_file_id")
- seen.add(client_id)
- local = self.by_id[client_id]
- if item.get("file_name") != local.path.name or item.get("bytes") != local.size:
+ file_id = item.get("file_id")
+ if not isinstance(file_id, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", file_id) or file_id in bindings:
+ raise ClientError("Invalid or duplicate file_id")
+ if self.by_id and self.by_id.get(file_id) is not local:
+ raise ClientError("Task file identity or order changed")
+ if item.get("file_name") != local.path.name or (details and item.get("bytes") != local.size):
raise ClientError("Task files differ from local inputs; use the original file list and order")
- if "upload" not in item:
- raise ClientError("Missing file upload descriptor")
- link = item["upload"]
+ bindings[file_id] = local
+ if item.get("status") not in {"waiting-file", "pending", "running", "completed", "failed", "canceled"}:
+ raise ClientError("Unknown file status")
+ link = item.get("upload")
if link is None:
continue
if not isinstance(link, dict):
@@ -273,22 +274,27 @@ class TaskClient:
raise ClientError("Invalid upload headers or expiry")
if item["status"] != "waiting-file" or payload["status"] in TERMINAL:
raise ClientError("Upload descriptor does not match file state")
+ self.task_id = task_id
+ self.by_id = bindings
+ return payload
+
+ def validate_creation(self, payload: dict[str, Any]) -> dict[str, Any]:
+ """创建回执仅确认身份和上传动作,不要求详情中的大小、格式或结果字段。"""
+ return self._validate_file_map(payload, details=False)
+
+ def validate_task(self, payload: dict[str, Any]) -> dict[str, Any]:
+ """独立校验 GET 详情和产物契约,省略字段表示当前没有该值。"""
+ payload = self._validate_file_map(payload, details=True)
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-file", "pending", "running", "completed", "failed", "canceled"}:
- raise ClientError("Unknown file status")
+ expected = list(dict.fromkeys(value.strip() for value in os.environ.get("OUTPUT_FORMATS", "default").split(",")))
+ if not isinstance(formats, list) or not formats or formats != expected:
+ raise ClientError("Task output_formats differ from the original request")
+ for item in payload["files"]:
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
return payload
def create(self) -> dict[str, Any]:
@@ -331,17 +337,17 @@ class TaskClient:
def upload_missing(self, task: dict[str, Any]) -> dict[str, Any]:
"""逐文件上传与恢复,成功 PUT 或已进入后续阶段的文件不重复发送。"""
for original in task["files"]:
- client_id = original["client_file_id"]
- local = self.by_id[client_id]
- link = original["upload"]
+ file_id = original["file_id"]
+ local = self.by_id[file_id]
+ link = original.get("upload")
if original["status"] != "waiting-file":
- self.uploaded_ids.add(client_id)
- if link is None or client_id in self.uploaded_ids:
+ self.uploaded_ids.add(file_id)
+ if link is None or file_id in self.uploaded_ids:
continue
- if self.upload_attempts.get(client_id, 0) >= 3:
+ if self.upload_attempts.get(file_id, 0) >= 3:
raise ClientError(f"Upload failed after three attempts: {local.path.name}")
- for attempt in range(self.upload_attempts.get(client_id, 0), 3):
- self.upload_attempts[client_id] = attempt + 1
+ for attempt in range(self.upload_attempts.get(file_id, 0), 3):
+ self.upload_attempts[file_id] = attempt + 1
def upload_body() -> Generator[bytes, None, None]:
"""每次重试重新打开同一个文件,单文件从头重传。"""
@@ -357,18 +363,18 @@ class TaskClient:
) as response:
if not 200 <= response.status < 300:
raise self._http_error(response)
- self.uploaded_ids.add(client_id)
+ self.uploaded_ids.add(file_id)
break
except ClientError as exc:
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)
+ remote = next(item for item in current["files"] if item["file_id"] == file_id)
if remote["status"] != "waiting-file":
- self.uploaded_ids.add(client_id)
+ self.uploaded_ids.add(file_id)
break
- replacement = remote["upload"]
+ replacement = remote.get("upload")
if replacement is None:
break
if exc.status == 403 and replacement["url"] == link["url"]:
@@ -429,7 +435,7 @@ class TaskClient:
if attempt == 2 or (not exc.retryable and exc.status not in {401, 403, 404}):
raise
current = self.refresh_after_transfer_error()
- remote = next(item for item in current["files"] if item["client_file_id"] == file["client_file_id"])
+ remote = next(item for item in current["files"] if item["file_id"] == file["file_id"])
if remote["status"] != "completed":
raise ClientError("File no longer has a downloadable result") from exc
replacement = self.resolve(remote["result_url"])
@@ -441,16 +447,16 @@ class TaskClient:
temporary.unlink(missing_ok=True)
def download_completed(self, task: dict[str, Any], output: Path) -> None:
- """按 client_file_id 保存独立结果,同名输入和多次轮询不会相互覆盖。"""
+ """按 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:
+ file_id = file["file_id"]
+ if file["status"] != "completed" or file_id in self.saved_ids:
continue
- destination = output / client_id / (self.by_id[client_id].path.stem + "." + extension)
+ destination = output / file_id / (self.by_id[file_id].path.stem + "." + extension)
self.download(task, file, destination)
- self.saved_ids.add(client_id)
+ self.saved_ids.add(file_id)
print(f"Saved {destination}")
def run(self, output: Path) -> int:
@@ -462,10 +468,12 @@ class TaskClient:
else:
task = self.create()
print(f"task_id={self.task_id}", file=sys.stderr)
+ if not resume:
+ task = self.refresh()
self.download_completed(task, output)
for original in list(task["files"]):
- current = next(item for item in task["files"] if item["client_file_id"] == original["client_file_id"])
- if current["upload"] is None:
+ current = next(item for item in task["files"] if item["file_id"] == original["file_id"])
+ if current.get("upload") is None:
continue
task = self.upload_missing({**task, "files": [current]})
self.download_completed(task, output)
@@ -483,9 +491,7 @@ class TaskClient:
raise
continue
if any(
- item["status"] == "waiting-file"
- and item["upload"] is not None
- and item["client_file_id"] not in self.uploaded_ids
+ item["status"] == "waiting-file" and item.get("upload") is not None and item["file_id"] not in self.uploaded_ids
for item in task["files"]
):
task = self.upload_missing(task)
@@ -511,7 +517,7 @@ def main(arguments: list[str]) -> int:
if send_hash not in {"0", "1"}:
raise ClientError("SEND_HASH must be 0 or 1")
inputs: list[InputFile] = []
- for index, value in enumerate(arguments):
+ for value in arguments:
path = Path(value).resolve()
if not path.is_file() or path.stat().st_size == 0:
raise ClientError(f"Input must be a non-empty file: {value}")
@@ -519,7 +525,7 @@ def main(arguments: list[str]) -> int:
if hasher is not None:
for chunk in _file_body(path):
hasher.update(chunk)
- inputs.append(InputFile(path, f"f{index + 1}", path.stat().st_size, hasher.hexdigest() if hasher else None))
+ inputs.append(InputFile(path, path.stat().st_size, hasher.hexdigest() if hasher else None))
client = TaskClient(inputs)
return client.run(Path(os.environ.get("RESULT_DIR", "results")))
except (ClientError, OSError, ValueError) as exc:
diff --git a/tests/unittest/task_test_utils.py b/tests/unittest/task_test_utils.py
index 0f43d693..5cb2bdb1 100644
--- a/tests/unittest/task_test_utils.py
+++ b/tests/unittest/task_test_utils.py
@@ -22,8 +22,8 @@ def task_url(client: TestClient | httpx.Client | httpx.AsyncClient, task: dict[s
def pending_files(task: dict[str, Any]) -> list[dict[str, Any]]:
- """从真实逐文件快照选取待上传项,缺少新 upload 字段时直接失败。"""
- return [item for item in task["files"] if item["upload"] is not None]
+ """从真实逐文件快照选取带上传动作的条目,省略字段时只轮询。"""
+ return [item for item in task["files"] if item.get("upload") is not None]
def stored_source(store: FileStore, path: Path) -> dict[str, str]:
@@ -53,7 +53,6 @@ def submit_task(client: TestClient, path: Path, **options: Any) -> dict[str, Any
json={
"files": [
{
- "client_file_id": "file",
"file_name": path.name,
"bytes": len(data),
"sha256sum": hashlib.sha256(data).hexdigest(),
@@ -65,7 +64,7 @@ def submit_task(client: TestClient, path: Path, **options: Any) -> dict[str, Any
assert response.status_code == 202, response.text
task = response.json()
for link in pending_files(task):
- response = client.put(link["upload"]["url"], content=data, headers=link["upload"]["headers"])
+ response = client.put(link.get("upload").get("url"), content=data, headers=link.get("upload")["headers"])
assert response.status_code < 400, response.text
return task
diff --git a/tests/unittest/test_engine_dead_lifecycle.py b/tests/unittest/test_engine_dead_lifecycle.py
index 649586a2..f515dd8f 100644
--- a/tests/unittest/test_engine_dead_lifecycle.py
+++ b/tests/unittest/test_engine_dead_lifecycle.py
@@ -66,7 +66,7 @@ def test_api_engine_failure_drains_running_and_queued_jobs(tmp_path: Path, monke
source = tmp_path / f"{name}.pdf"
source.write_bytes(name.encode())
jobs.append(submit_task(client, source, tier="flash"))
- assert client.delete(task_url(client, jobs[-1])).status_code == 200
+ assert client.post(task_url(client, jobs[-1]) + "/cancel").status_code == 200
client.portal.call(gate.set)
for job in jobs:
wait_task(client, job)
@@ -94,15 +94,15 @@ def test_api_engine_failure_drains_running_and_queued_jobs(tmp_path: Path, monke
for path, method in (("/v1/health", "get"), ("/v1/tasks", "post")):
response = getattr(client, method)(
path,
- **(
- {"json": {"tier": "flash", "files": [{"client_file_id": "file", "file_name": "new.pdf", "bytes": 3}]}}
- if method == "post"
- else {}
- ),
+ **({"json": {"tier": "flash", "files": [{"file_name": "new.pdf", "bytes": 3}]}} if method == "post" else {}),
)
- assert response.status_code == 503 and response.json()["error"]["code"] == "engine_dead"
+ assert response.status_code == 503 and response.json().get("error")["code"] == "engine_dead"
assert app.state.job_store._semaphore._value == 2
assert not app.state.job_store._tasks
+ assert not app.state.file_store._reserved_output_ids
+ for job in jobs:
+ file_id = job["files"][0]["file_id"]
+ assert client.get(f"/v1/files/{file_id}").status_code == 404
def test_router_single_generation_replacement_and_backoff(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -200,7 +200,7 @@ def test_old_generation_failure_snapshot_remains_queryable() -> None:
execution = client.portal.call(snapshot)
assert execution.job["status"] == "failed"
- assert execution.job["files"][0]["error"]["code"] == "upstream_task_lost"
+ assert execution.job["files"][0].get("error")["code"] == "upstream_task_lost"
pool._workers = {state.worker_id: state}
reservation = pool.reserve_job(tier="standard", required_sources={"upload"})
assert reservation is not None and reservation.worker is state
diff --git a/tests/unittest/test_file_parse.py b/tests/unittest/test_file_parse.py
index 89b30e52..e1f0bbff 100644
--- a/tests/unittest/test_file_parse.py
+++ b/tests/unittest/test_file_parse.py
@@ -82,7 +82,7 @@ class Upstream:
"output_formats": task["options"]["output_formats"],
"files": [
{
- "client_file_id": "file",
+ "file_id": f"file-{task_id}",
"file_name": task["options"]["files"][0]["file_name"],
"bytes": task["options"]["files"][0]["bytes"],
"status": status,
@@ -113,6 +113,7 @@ class Upstream:
return httpx.Response(401, json={"error": {"code": "invalid_api_key", "message": "Bad upstream key"}})
body = json.loads(await request.aread())
assert len(body["files"]) == 1
+ assert {"client_file_id", "file_id"}.isdisjoint(body["files"][0])
task_id = f"task_{len(self.tasks) + 1}"
self.tasks[task_id] = {
"options": body,
@@ -126,7 +127,20 @@ class Upstream:
payload = self.payload(task_id)
if self.create_failure == "malformed":
payload["task_id"] = None
- return httpx.Response(202, json=payload)
+ return httpx.Response(
+ 202,
+ json={
+ "task_id": payload["task_id"],
+ "status": payload["status"],
+ "files": [
+ {
+ key: value
+ for key, value in payload["files"][0].items()
+ if key in {"file_id", "file_name", "status", "upload"} and value is not None
+ }
+ ],
+ },
+ )
task_id = request.url.path.rsplit("/", 1)[-1]
task = self.tasks[task_id]
if request.method == "PUT":
@@ -383,8 +397,8 @@ def test_new_protocol_preserves_but_does_not_restore_legacy_records(tmp_path: Pa
upstream = Upstream()
settings = FileParseSettings(upstream.api_url, "secret", tmp_path)
legacy_namespace = hashlib.sha256(f"{settings.api_url}\0secret".encode()).hexdigest()
- assert settings.namespace == "tasks-v4-" + legacy_namespace
- legacy = tmp_path / ("tasks-v3-" + legacy_namespace)
+ assert settings.namespace == "tasks-v5-" + legacy_namespace
+ legacy = tmp_path / ("tasks-v4-" + legacy_namespace)
source = legacy / "sources" / "old-input"
source.parent.mkdir(parents=True)
source.write_bytes(b"old source")
@@ -699,3 +713,42 @@ def test_cli_configuration_and_environment(tmp_path: Path, monkeypatch: pytest.M
)
assert result.exit_code == 0, result.output
assert captured[0][1] == {"host": "127.0.0.1", "port": 8003}
+
+
[email protected]("cached", [False, True])
+def test_restart_after_creation_receipt_and_failed_first_query(tmp_path: Path, cached: bool) -> None:
+ """创建成功后查询失败仍先持久化 ID,重启仅恢复原任务,包括已完成的缓存回执。"""
+
+ class FailingQueries(Upstream):
+ """把首次进程的详情查询固定为临时失败,保留创建和对象存储行为。"""
+
+ fail_queries = True
+
+ async def handle(self, request: httpx.Request) -> httpx.Response:
+ """让失败发生在已确认创建之后,避免测试误走创建结果未知分支。"""
+ if self.fail_queries and request.method == "GET" and "/v1/tasks/" in request.url.path:
+ return httpx.Response(503, json={"error": {"code": "temporary", "message": "retry query"}})
+ return await super().handle(request)
+
+ upstream = FailingQueries()
+ upstream.cache_hit = cached
+ app = application(tmp_path, upstream)
+ with TestClient(app) as client:
+ app.state.service.client.retry_delay = 0
+ response = submit(client)
+ assert response.status_code == 502, response.text
+ record = app.state.service.records["request_1"]
+ assert record.task.task_id == "task_1"
+ assert record.task.files[0].file_id == "file-task_1"
+ assert not record.task.details_loaded
+ assert record.status != "submission_unknown"
+ if not cached:
+ assert Path(record.source_path).is_file()
+ upstream.fail_queries = False
+ with TestClient(application(tmp_path, upstream)) as client:
+ response = submit(client)
+ assert response.status_code == 200, response.text
+ assert response.content == artifact_bytes(["default"])
+ state = client.get("/v1/file_parse/request_1").json()
+ assert state["task_id"] == "task_1" and state["status"] == "completed"
+ assert len(upstream.tasks) == 1 and upstream.uploads == (0 if cached else 1)
diff --git a/tests/unittest/test_flash_html.py b/tests/unittest/test_flash_html.py
index 03587a94..faa62f5a 100644
--- a/tests/unittest/test_flash_html.py
+++ b/tests/unittest/test_flash_html.py
@@ -227,11 +227,11 @@ def test_html_parse_server_flash_only_admits_extensionless_url(
with TestClient(app) as client:
response = client.post(
"/v1/tasks",
- json={"files": [{"client_file_id": "file", "file_name": "article.html", "url": "https://example.com/article"}]},
+ json={"files": [{"file_name": "article.html", "url": "https://example.com/article"}]},
)
assert response.status_code == 202
- assert response.json()["tier"] == "flash"
+ assert app.state.task_store._records[response.json()["task_id"]].options.tier == "flash"
def test_html_parse_server_no_flash_rejects_extensionless_text_html_after_fetch(
diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.py
index 12b679d9..1d0a94a4 100644
--- a/tests/unittest/test_parser_api_contract.py
+++ b/tests/unittest/test_parser_api_contract.py
@@ -575,9 +575,9 @@ def test_api_server_validation_errors_use_error_envelope(tmp_path: Path, monkeyp
assert response.status_code == 400
body = response.json()
assert "detail" not in body
- assert body["error"]["type"] == "invalid_request_error"
- assert body["error"]["code"] == "invalid_request"
- assert "Invalid request" in body["error"]["message"]
+ assert body.get("error")["type"] == "invalid_request_error"
+ assert body.get("error")["code"] == "invalid_request"
+ assert "Invalid request" in body.get("error")["message"]
def test_api_server_unhandled_exceptions_use_error_envelope(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
@@ -595,7 +595,7 @@ def test_api_server_unhandled_exceptions_use_error_envelope(tmp_path: Path, monk
assert response.status_code == 500
body = response.json()
assert "detail" not in body
- assert body["error"] == {
+ assert body.get("error") == {
"type": "api_error",
"code": "internal_error",
"message": "Internal server error",
@@ -868,7 +868,7 @@ def test_api_server_model_detail_rejects_unknown_id(tmp_path: Path, monkeypatch:
response = client.get("/v1/models/MinerU2.5-Pro-2605-1.2B")
assert response.status_code == 404
- assert response.json()["error"]["code"] == "model_not_found"
+ assert response.json().get("error")["code"] == "model_not_found"
def test_api_server_no_advanced_http_metadata_keeps_shared_models(
@@ -907,12 +907,12 @@ def test_api_server_model_preload_failure_keeps_health_diagnostics_and_rejects_c
models_response = client.get("/v1/models")
assert health_response.status_code == 503
- assert health_response.json()["error"]["code"] == "model_preload_device_unavailable"
- assert health_response.json()["error"]["message"] == "CUDA is not available."
+ assert health_response.json().get("error")["code"] == "model_preload_device_unavailable"
+ assert health_response.json().get("error")["message"] == "CUDA is not available."
assert tiers_response.status_code == 503
- assert tiers_response.json()["error"]["code"] == "model_preload_device_unavailable"
+ assert tiers_response.json().get("error")["code"] == "model_preload_device_unavailable"
assert models_response.status_code == 503
- assert models_response.json()["error"]["code"] == "model_preload_device_unavailable"
+ assert models_response.json().get("error")["code"] == "model_preload_device_unavailable"
def test_api_server_model_preload_is_opt_in_and_ignored_for_flash(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
@@ -1010,7 +1010,7 @@ def test_api_server_basic_rejects_advanced_request(tmp_path: Path, monkeypatch:
response = client.post(
"/v1/tasks",
json={
- "files": [{"client_file_id": "file", "file_name": source.name, "bytes": source.stat().st_size}],
+ "files": [{"file_name": source.name, "bytes": source.stat().st_size}],
"tier": "advanced",
},
)
@@ -1034,7 +1034,7 @@ def test_api_server_no_advanced_rejects_advanced_request(tmp_path: Path, monkeyp
response = client.post(
"/v1/tasks",
json={
- "files": [{"client_file_id": "file", "file_name": source.name, "bytes": source.stat().st_size}],
+ "files": [{"file_name": source.name, "bytes": source.stat().st_size}],
"tier": "advanced",
},
)
@@ -1056,7 +1056,7 @@ def test_api_server_no_flash_rejects_flash_request(tmp_path: Path, monkeypatch:
response = TestClient(app).post(
"/v1/tasks",
json={
- "files": [{"client_file_id": "file", "file_name": source.name, "bytes": source.stat().st_size}],
+ "files": [{"file_name": source.name, "bytes": source.stat().st_size}],
"tier": "flash",
},
)
diff --git a/tests/unittest/test_parser_api_ocr.py b/tests/unittest/test_parser_api_ocr.py
index cf5749b6..604c317c 100644
--- a/tests/unittest/test_parser_api_ocr.py
+++ b/tests/unittest/test_parser_api_ocr.py
@@ -37,10 +37,12 @@ def test_api_parser_serializes_request_ocr_mode(
def respond(request: httpx.Request) -> httpx.Response:
"""记录完整任务请求,在产物下载前返回已完成任务。"""
if request.method == "GET":
- return httpx.Response(200, content=zip_output())
+ if request.url.host == "storage.test":
+ return httpx.Response(200, content=zip_output())
+ return httpx.Response(200, json=task_snapshot(file_name=source.name, size=source.stat().st_size))
assert request.method == "POST" and request.url.path == "/v1/tasks"
payloads.append(json.loads(request.content))
- return httpx.Response(202, json=task_snapshot())
+ return httpx.Response(202, json=task_snapshot(file_name=source.name, size=source.stat().st_size))
transport = httpx.MockTransport(respond)
sync_client, async_client = httpx.Client, httpx.AsyncClient
@@ -63,7 +65,6 @@ def test_api_parser_serializes_request_ocr_mode(
expected: dict[str, Any] = {
"files": [
{
- "client_file_id": "file",
"file_name": source.name,
"bytes": source.stat().st_size,
"sha256sum": api_client._sha256_file(source),
@@ -93,19 +94,19 @@ def test_api_server_rejects_invalid_request_ocr_mode(tmp_path: Path, value: obje
response = client.post(
"/v1/tasks",
json={
- "files": [{"client_file_id": "file", "file_name": "demo.pdf", "bytes": 9}],
+ "files": [{"file_name": "demo.pdf", "bytes": 9}],
"ocr_mode": value,
},
)
assert response.status_code == 400
- assert response.json()["error"]["code"] == "invalid_request"
- assert response.json()["error"]["param"] == "ocr_mode"
+ assert response.json().get("error")["code"] == "invalid_request"
+ assert response.json().get("error")["param"] == "ocr_mode"
assert app.state.job_store._jobs == {}
def test_api_server_ocr_defaults_to_request_auto_without_startup_configuration(tmp_path: Path) -> None:
"""请求缺省值固定为 auto,应用生命周期不保存全局 OCR 模式。"""
- request = CreateTaskRequest.model_validate({"files": [{"client_file_id": "file", "file_name": "demo.pdf", "bytes": 9}]})
+ request = CreateTaskRequest.model_validate({"files": [{"file_name": "demo.pdf", "bytes": 9}]})
assert request.ocr_mode == "auto"
app = api_server.create_app(upload_dir=str(tmp_path), tier="flash")
assert not hasattr(app.state, "ocr_mode")
diff --git a/tests/unittest/test_parser_api_status.py b/tests/unittest/test_parser_api_status.py
index aa1ebe01..7df9f319 100644
--- a/tests/unittest/test_parser_api_status.py
+++ b/tests/unittest/test_parser_api_status.py
@@ -69,7 +69,7 @@ def test_parse_notifies_submission_and_polls_before_result_building(
assert durations == [250.0]
return httpx.Response(200, content=build_default_zip(result))
methods.append(request.method)
- status = next(replies)
+ status = next(replies, statuses[-1])
return httpx.Response(
200,
json={
@@ -78,7 +78,9 @@ def test_parse_notifies_submission_and_polls_before_result_building(
"output_formats": ["default"],
"files": [
{
- "client_file_id": "file",
+ "file_id": "file-one",
+ "file_name": source.name,
+ "bytes": source.stat().st_size,
"upload": None,
"status": "completed" if status == "partial" else status,
"parse": {"duration_ms": 250},
@@ -126,8 +128,8 @@ def test_parse_notifies_submission_and_polls_before_result_building(
else:
assert parse().middle_json == result.middle_json
assert notifications == list(statuses)
- assert methods == ["POST", *(["GET"] * (len(statuses) - 1))]
- assert delays == [1] * (len(statuses) - 1)
+ assert methods == ["POST", *(["GET"] * max(1, len(statuses) - 1))]
+ assert delays == [1] * max(0, len(statuses) - 2)
assert callback_errors == (["Parse job status callback failed"] * len(statuses) if callback_raises else [])
diff --git a/tests/unittest/test_pdf_page_id.py b/tests/unittest/test_pdf_page_id.py
index 3f1b2619..ec748b3e 100644
--- a/tests/unittest/test_pdf_page_id.py
+++ b/tests/unittest/test_pdf_page_id.py
@@ -177,17 +177,22 @@ def test_api_rejects_bad_ranges_before_creating_jobs(tmp_path: Path) -> None:
json={
"tier": "flash",
"files": [
- {"client_file_id": "first", "file_name": "a.pdf", "bytes": 1},
- {"client_file_id": "second", "file_name": "b.pdf", "bytes": 1, "page_range": raw},
+ {"file_name": "a.pdf", "bytes": 1},
+ {"file_name": "b.pdf", "bytes": 1, "page_range": raw},
],
},
)
assert response.status_code == 400
- error = response.json()["error"]
+ error = response.json().get("error")
assert error["code"] == "page_range_invalid"
assert error["param"] == "files.1.page_range"
schema = client.get("/openapi.json").json()
- assert "r1" in schema["components"]["schemas"]["TaskFileStatus"]["properties"]["page_range"]["description"]
+ assert (
+ "r1"
+ in schema["paths"]["/v1/tasks"]["post"]["requestBody"]["content"]["application/json"]["schema"]["properties"][
+ "files"
+ ]["items"]["properties"]["page_range"]["description"]
+ )
def test_cli_rejects_old_syntax_and_kit_preserves_range_error(tmp_path: Path) -> None:
diff --git a/tests/unittest/test_resource_retention.py b/tests/unittest/test_resource_retention.py
index 1579086e..0956fcbb 100644
--- a/tests/unittest/test_resource_retention.py
+++ b/tests/unittest/test_resource_retention.py
@@ -242,11 +242,11 @@ def test_hash_preflight_rejection_releases_request_lease(tmp_path: Path, monkeyp
"/v1/tasks",
json={
"tier": "flash",
- "files": [{"client_file_id": "f1", "file_name": "input.pdf", "bytes": 3, "sha256sum": sha}],
+ "files": [{"file_name": "input.pdf", "bytes": 3, "sha256sum": sha}],
},
)
assert response.status_code == 400
- assert response.json()["error"]["code"] == "upload_size_mismatch"
+ assert response.json().get("error")["code"] == "upload_size_mismatch"
assert not app.state.file_store._pins and not app.state.job_store._jobs
@@ -360,4 +360,4 @@ def test_external_worker_lost_task_releases_load_and_keeps_snapshot() -> None:
client.portal.call(_reconcile_jobs_once, app.state.registry, pool)
assert reservation.worker.active_jobs == 0
assert route.metadata["payload"]["status"] == "failed"
- assert route.metadata["payload"]["files"][0]["error"]["code"] == "upstream_task_lost"
+ assert route.metadata["payload"]["files"][0].get("error")["code"] == "upstream_task_lost"
diff --git a/tests/unittest/test_router_balancing.py b/tests/unittest/test_router_balancing.py
index 8492d5a6..2707b0bc 100644
--- a/tests/unittest/test_router_balancing.py
+++ b/tests/unittest/test_router_balancing.py
@@ -20,7 +20,7 @@ from mineru.parser import api_server
from mineru.kit.router import RouterSettings, create_app
from mineru.kit.router.workers import JobReservation
-BODY = {"tier": "standard", "files": [{"client_file_id": "file", "file_name": "source.pdf", "bytes": 5}]}
+BODY = {"tier": "standard", "files": [{"file_name": "source.pdf", "bytes": 5}]}
@pytest.mark.parametrize("formats", [["unknown"], "markdown", None, 1, {}, [{}], [1]])
@@ -36,7 +36,7 @@ def test_output_format_validation_precedes_worker_selection(formats: Any, tmp_pa
with TestClient(app, raise_server_exceptions=False) as client:
response = client.post("/v1/tasks", json=body)
assert response.status_code == expected.status_code == 400, response.text
- assert response.json()["error"]["code"] == expected.json()["error"]["code"]
+ assert response.json().get("error")["code"] == expected.json().get("error")["code"]
assert not app.state.registry.list("job")
assert app.state.worker_pool.workers[0].active_jobs == 0
@@ -81,7 +81,6 @@ def test_task_auth_preflight_uses_a_capable_worker_without_reservation() -> None
"tier": "standard",
"files": [
{
- "client_file_id": "f1",
"file_name": "source.pdf",
"bytes": 3,
}
@@ -199,7 +198,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["files"][0]["result_url"] is None
+ assert failed["status"] == "failed" and failed["files"][0].get("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_router_cascade.py b/tests/unittest/test_router_cascade.py
index b3c1654d..24c5b04c 100644
--- a/tests/unittest/test_router_cascade.py
+++ b/tests/unittest/test_router_cascade.py
@@ -88,7 +88,6 @@ async def _submit(client: httpx.AsyncClient, *, filename: str = "input.html", ur
"tier": "flash",
"files": [
{
- "client_file_id": "file",
"file_name": filename,
"bytes": len(HTML),
"sha256sum": hashlib.sha256(HTML).hexdigest(),
@@ -115,7 +114,7 @@ async def _terminal(client: httpx.AsyncClient, task: dict[str, Any]) -> dict[str
async def _check_download(client: httpx.AsyncClient, result: dict[str, Any]) -> None:
"""验证逐跳 Files 代理返回真实且内容完整的解析 ZIP。"""
- response = await client.get(result["files"][0]["result_url"])
+ response = await client.get(result["files"][0].get("result_url"))
assert response.status_code == 200, response.text
with zipfile.ZipFile(io.BytesIO(response.content)) as archive:
assert b"Cascade document" in archive.read("markdown.md")
@@ -129,15 +128,16 @@ def test_cascade_accepts_ready_upload_without_source_file_and_reuses_cache(tmp_p
"""通过提交等待固定竞争窗口,验证内外层均不提前判错。"""
async with _cascade(tmp_path, block_submission=True) as (client, outer, inner, worker, transport):
task = await _submit(client)
- response = await client.put(pending_files(task)[0]["upload"]["url"], content=HTML)
+ response = await client.put(pending_files(task)[0].get("upload").get("url"), content=HTML)
assert response.status_code == 200, response.text
await asyncio.wait_for(transport.submission_started.wait(), timeout=5)
inner_record = next(iter(inner.state.task_store._records.values()))
inner_route = outer.state.registry.list("job")[0]
ready = await outer.state.worker_pool.client.get(f"http://inner/v1/tasks/{inner_route.upstream_id}")
assert ready.json()["files"][0]["status"] == "pending"
- assert ready.json()["files"][0]["upload"] is None
- assert "file_id" not in ready.json()["files"][0]
+ assert ready.json()["files"][0].get("upload") is None
+ assert ready.json()["files"][0]["file_id"] == inner_record.inputs[0].file_id
+ assert ready.json()["files"][0]["file_id"] != task["files"][0]["file_id"]
async with asyncio.timeout(5):
while not outer.state.task_store._records[task["task_id"]].file_states[0].submitted:
await asyncio.sleep(0.01)
@@ -149,7 +149,8 @@ def test_cascade_accepts_ready_upload_without_source_file_and_reuses_cache(tmp_p
transport.allow_submission.set()
result = await _terminal(client, task)
assert result["status"] == "completed", result
- assert "file_id" not in result["files"][0]
+ assert result["files"][0]["file_id"] == task["files"][0]["file_id"]
+ assert result["files"][0]["result_url"].endswith(f"/{task['files'][0]['file_id']}/content")
await _check_download(client, result)
cached = await _submit(client, filename="renamed.html")
assert pending_files(cached) == []
@@ -169,10 +170,10 @@ def test_cascade_can_cancel_while_downstream_submission_is_blocked(tmp_path: Pat
"""阻塞实际任务提交后取消外层父任务,确认没有遗留解析或缓存租约。"""
async with _cascade(tmp_path, block_submission=True) as (client, outer, inner, worker, transport):
task = await _submit(client)
- response = await client.put(pending_files(task)[0]["upload"]["url"], content=HTML)
+ response = await client.put(pending_files(task)[0].get("upload").get("url"), content=HTML)
assert response.status_code == 200, response.text
await asyncio.wait_for(transport.submission_started.wait(), timeout=5)
- response = await client.delete(task_url(client, task))
+ response = await client.post(task_url(client, task) + "/cancel")
assert response.status_code == 200, response.text
assert response.json()["status"] == "canceled"
async with asyncio.timeout(5):
diff --git a/tests/unittest/test_task_api.py b/tests/unittest/test_task_api.py
index 8519f291..6db1aa51 100644
--- a/tests/unittest/test_task_api.py
+++ b/tests/unittest/test_task_api.py
@@ -69,19 +69,18 @@ def _source_references(app: FastAPI, task: dict[str, Any]) -> set[str]:
def _delete_source_references(client: TestClient, app: FastAPI, references: set[str]) -> None:
- """删除旧源引用以复现共享字节竞争,Router 私有引用不经过 Files HTTP。"""
+ """通过内部清理旧源引用复现共享字节竞争,不依赖公开删除接口。"""
assert references
for reference in references:
if hasattr(app.state, "source_store"):
client.portal.call(app.state.source_store.delete_file, reference)
else:
- assert client.delete(f"/v1/files/{reference}").status_code == 200
+ client.portal.call(app.state.file_store.delete_file, reference)
def _url_manifest(**metadata: Any) -> dict[str, Any]:
"""构造与下载地址名称无关的逻辑文件条目,默认不声明大小或 hash。"""
return {
- "client_file_id": "remote",
"file_name": "logical.html",
"url": "https://source.example/opaque?signature=a%2Fb&part=1",
**metadata,
@@ -138,29 +137,33 @@ def _submit(
headers: dict[str, str] | None = None,
**options: str | list[str],
) -> dict[str, Any]:
- """只用 JSON 提交真实大小及可选 SHA-256,绝不在创建请求中发送多个文件。"""
+ """创建真实任务并读取初始详情,响应模型本身由独立契约测试覆盖。"""
manifest = [
{
- "client_file_id": f"f{index + 1}",
"file_name": name,
"bytes": len(data),
**({"sha256sum": hashlib.sha256(data).hexdigest()} if hashes else {}),
}
- for index, (name, data) in enumerate(inputs)
+ for name, data in inputs
]
response = client.post("/v1/tasks", json={"files": manifest, "tier": "flash", **options}, headers=headers)
assert response.status_code == 202, response.text
- return response.json()
+ detail = client.get(task_url(client, response.json()), headers=headers)
+ assert detail.status_code == 200, detail.text
+ return detail.json()
def _upload(
client: TestClient, task: dict[str, Any], inputs: list[tuple[str, bytes]], *, headers: dict[str, str] | None = None
) -> None:
- """仅上传返回链接对应的缺失文件,按 client_file_id 保持同名文件的关联。"""
- for link in pending_files(task):
- index = int(link["client_file_id"][1:]) - 1
+ """仅上传返回链接对应的缺失文件,按 file_id 保持同名文件的关联。"""
+ for index, link in enumerate(task["files"]):
+ if link.get("upload") is None:
+ continue
response = client.put(
- link["upload"]["url"], content=inputs[index][1], headers={**link["upload"]["headers"], **(headers or {})}
+ link.get("upload").get("url"),
+ content=inputs[index][1],
+ headers={**link.get("upload")["headers"], **(headers or {})},
)
assert response.status_code == 200, response.text
@@ -174,7 +177,7 @@ 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 all(file["result_url"] is None for file in payload["files"] if file["status"] != "completed")
+ assert all(file.get("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")
@@ -192,8 +195,8 @@ def _file_done(client: TestClient, task: dict[str, Any], index: int) -> dict[str
def _archive(client: TestClient, task: dict[str, Any], index: int = 0) -> dict[str, bytes]:
"""从返回的独立 Files 链接下载并读取真实 ZIP 成员。"""
- assert "/v1/files/" in task["files"][index]["result_url"]
- response = client.get(task["files"][index]["result_url"])
+ assert "/v1/files/" in task["files"][index].get("result_url")
+ response = client.get(task["files"][index].get("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:
@@ -215,11 +218,11 @@ def test_manifest_uploads_and_zip_only_status(service: tuple[TestClient, FastAPI
task = _submit(client, inputs, hashes=hashes, output_formats=["default"])
assert task["status"] == "waiting-file" and "result_url" not in task
assert len(pending_files(task)) == 2 and _job_count(app) == 0
- assert client.put(pending_files(task)[0]["upload"]["url"], content=HTML).status_code == 200
+ assert client.put(pending_files(task)[0].get("upload").get("url"), content=HTML).status_code == 200
ready = _file_done(client, task, 0)
assert ready["status"] == "waiting-file"
assert [file["status"] for file in ready["files"]] == ["completed", "waiting-file"]
- assert [link["client_file_id"] for link in pending_files(ready)] == ["f2"]
+ assert [link["file_id"] for link in pending_files(ready)] == [task["files"][1]["file_id"]]
assert _job_count(app) == 1
assert b"Preserved content" in _archive(client, ready)["markdown.md"]
_upload(client, ready, inputs)
@@ -235,7 +238,7 @@ def test_manifest_uploads_and_zip_only_status(service: tuple[TestClient, FastAPI
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 all({"file_id", "name", "sha256sum", "page_range"}.isdisjoint(file) for file in result["files"])
+ assert all({"client_file_id", "name", "sha256sum", "page_range"}.isdisjoint(file) for file in result["files"])
def test_direct_and_form_submissions_are_rejected(service: tuple[TestClient, FastAPI]) -> None:
@@ -268,11 +271,11 @@ def test_mixed_cache_hit_survives_source_deletion(service: tuple[TestClient, Fas
old_references = _source_references(app, original)
inputs = [("renamed.html", HTML), ("new.html", SECOND)]
task = _submit(client, inputs)
- assert [link["client_file_id"] for link in pending_files(task)] == ["f2"]
- assert task["files"][0]["status"] == "pending" and task["files"][0]["upload"] is None
+ assert [link["file_id"] for link in pending_files(task)] == [task["files"][1]["file_id"]]
+ assert task["files"][0]["status"] in {"pending", "running", "completed"} and task["files"][0].get("upload") is None
_delete_source_references(client, app, old_references)
duplicate = client.put(
- f"/v1/tasks/{task['task_id']}/uploads/f1",
+ f"/v1/tasks/{task['task_id']}/uploads/{task['files'][0]['file_id']}",
content=_UnreadableBody(),
headers={"content-length": str(len(HTML)), "expect": "100-continue"},
)
@@ -281,7 +284,7 @@ def test_mixed_cache_hit_survives_source_deletion(service: tuple[TestClient, Fas
result = _terminal(client, task)
assert result["status"] == "completed" and result["files"][0]["file_name"] == "renamed.html"
cached = _submit(client, inputs)
- assert pending_files(cached) == [] and cached["status"] == "pending"
+ assert pending_files(cached) == [] and cached["status"] in {"pending", "running", "completed"}
assert _terminal(client, cached)["status"] == "completed"
assert _job_count(app) == 5
@@ -305,10 +308,10 @@ def test_waiting_file_retains_deleted_source_views(service: tuple[TestClient, Fa
client, app = service
inputs = [("a.html", HTML), ("b.html", SECOND)]
task = _submit(client, inputs, hashes=False)
- assert client.put(pending_files(task)[0]["upload"]["url"], content=HTML).status_code == 200
+ assert client.put(pending_files(task)[0].get("upload").get("url"), content=HTML).status_code == 200
ready = _file_done(client, task, 0)
_delete_source_references(client, app, _source_references(app, ready))
- assert client.put(pending_files(task)[1]["upload"]["url"], content=SECOND).status_code == 200
+ assert client.put(pending_files(task)[1].get("upload").get("url"), content=SECOND).status_code == 200
result = _terminal(client, task)
assert result["status"] == "completed", result
assert b"Preserved content" in _archive(client, result)["markdown.md"]
@@ -319,11 +322,11 @@ def test_failed_upload_can_retry_without_reuploading_ready_file(service: tuple[T
client, app = service
inputs = [("a.html", HTML), ("b.html", SECOND)]
task = _submit(client, inputs)
- assert client.put(pending_files(task)[0]["upload"]["url"], content=HTML).status_code == 200
- failed = client.put(pending_files(task)[1]["upload"]["url"], content=SECOND.replace(b"Second", b"Broken"))
- assert failed.status_code == 400 and failed.json()["error"]["code"] == "file_hash_mismatch"
- mismatch = client.put(pending_files(task)[1]["upload"]["url"], content=SECOND + b"x")
- assert mismatch.status_code == 400 and mismatch.json()["error"]["code"] == "upload_size_mismatch"
+ assert client.put(pending_files(task)[0].get("upload").get("url"), content=HTML).status_code == 200
+ failed = client.put(pending_files(task)[1].get("upload").get("url"), content=SECOND.replace(b"Second", b"Broken"))
+ assert failed.status_code == 400 and failed.json().get("error")["code"] == "file_hash_mismatch"
+ mismatch = client.put(pending_files(task)[1].get("upload").get("url"), content=SECOND + b"x")
+ assert mismatch.status_code == 400 and mismatch.json().get("error")["code"] == "upload_size_mismatch"
pending = _file_done(client, task, 0)
assert pending["status"] == "waiting-file" and _job_count(app) == 1
assert pending["files"][0]["status"] in {"pending", "running", "completed"}
@@ -342,9 +345,9 @@ def test_concurrent_last_uploads_and_duplicate_put_submit_once(service: tuple[Te
"""在服务所属事件循环同时发起两个文件及同一文件的重复请求。"""
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") as asynchronous:
return await asyncio.gather(
- asynchronous.put(pending_files(task)[0]["upload"]["url"], content=HTML),
- asynchronous.put(pending_files(task)[1]["upload"]["url"], content=SECOND),
- asynchronous.put(pending_files(task)[1]["upload"]["url"], content=SECOND),
+ asynchronous.put(pending_files(task)[0].get("upload").get("url"), content=HTML),
+ asynchronous.put(pending_files(task)[1].get("upload").get("url"), content=SECOND),
+ asynchronous.put(pending_files(task)[1].get("upload").get("url"), content=SECOND),
)
responses = client.portal.call(upload_all)
@@ -360,25 +363,25 @@ def test_cancel_and_expire_waiting_file_release_inputs(service: tuple[TestClient
"""取消或上传过期只终结未完成文件,已生成结果继续可下载。"""
client, app = service
task = _submit(client, [("a.html", HTML), ("b.html", SECOND)])
- assert client.put(pending_files(task)[0]["upload"]["url"], content=HTML).status_code == 200
+ assert client.put(pending_files(task)[0].get("upload").get("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_url(client, task))
- assert response.json()["files"][1]["error"]["code"] == "upload_expired"
+ assert response.json()["files"][1].get("error")["code"] == "upload_expired"
assert response.json()["files"][1]["status"] == "failed"
else:
- response = client.delete(task_url(client, task))
+ response = client.post(task_url(client, task) + "/cancel")
assert response.status_code == 200
assert response.json()["status"] == ("partial" if expired else "canceled")
assert pending_files(response.json()) == [] and _job_count(app) == 1
- assert response.json()["files"][0]["result_url"] == ready["files"][0]["result_url"]
+ assert response.json()["files"][0].get("result_url") == ready["files"][0].get("result_url")
assert b"Preserved content" in _archive(client, response.json())["markdown.md"]
- rejected = client.put(pending_files(task)[1]["upload"]["url"], content=SECOND)
+ rejected = client.put(pending_files(task)[1].get("upload").get("url"), content=SECOND)
assert rejected.status_code == (410 if expired else 409)
if expired:
- assert client.put(pending_files(task)[0]["upload"]["url"], content=HTML).status_code == 410
+ assert client.put(pending_files(task)[0].get("upload").get("url"), content=HTML).status_code == 410
async def wait_cleanup() -> None:
"""等待父任务持有的清理句柄,避免按定时猜测引用是否已释放。"""
@@ -409,10 +412,10 @@ def test_cancel_running_task_releases_execution_slot(
task = _submit(client, [("a.html", HTML)])
_upload(client, task, [("a.html", HTML)])
assert started.wait(5)
- response = client.delete(task_url(client, task))
+ response = client.post(task_url(client, task) + "/cancel")
assert response.status_code == 200, response.text
assert response.json()["status"] == "canceled"
- assert client.get(task_url(client, task)).json()["files"][0]["result_url"] is None
+ assert client.get(task_url(client, task)).json()["files"][0].get("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():
@@ -469,8 +472,8 @@ def test_partial_and_packaging_failure_have_honest_results(
task = _submit(client, inputs)
_upload(client, task, inputs)
result = _terminal(client, task)
- assert result["status"] == "partial" and result["files"][1]["error"]
- assert result["files"][1]["result_url"] is None
+ assert result["status"] == "partial" and result["files"][1].get("error")
+ assert result["files"][1].get("result_url") is None
assert "markdown.md" in _archive(client, result)
original = task_outputs.build_task_output
@@ -485,18 +488,17 @@ def test_partial_and_packaging_failure_have_honest_results(
task = _submit(client, good)
_upload(client, task, good)
failed = _terminal(client, task)
- assert failed["status"] == "partial" and failed["files"][1]["result_url"] is None
- assert failed["files"][1]["error"]["code"] == "result_packaging_failed"
+ assert failed["status"] == "partial" and failed["files"][1].get("result_url") is None
+ assert failed["files"][1].get("error")["code"] == "result_packaging_failed"
assert "markdown.md" in _archive(client, failed)
def test_input_validation_and_openapi(service: tuple[TestClient, FastAPI]) -> None:
"""请求与 OpenAPI 都使用严格 JSON 数组,旧格式与额外字段在接单前拒绝。"""
client, app = service
- valid = {"client_file_id": "f1", "file_name": "a.html", "bytes": len(HTML)}
+ valid = {"file_name": "a.html", "bytes": len(HTML)}
for manifest in (
[],
- [valid] * 2,
[valid] * 101,
[{**valid, "bytes": 0}],
[{**valid, "sha256sum": "invalid"}],
@@ -531,78 +533,53 @@ def test_input_validation_and_openapi(service: tuple[TestClient, FastAPI]) -> No
assert files_schema["type"] == "array"
assert files_schema["minItems"] == 1 and files_schema["maxItems"] == 100
assert "file_name" in files_schema["items"]["required"]
- assert "client_file_id" not in files_schema["items"]["required"]
+ assert {"file_id", "client_file_id"}.isdisjoint(files_schema["items"]["properties"])
assert "filename" not in files_schema["items"]["properties"]
- id_schema = spec["components"]["schemas"]["TaskFileStatus"]
- assert "client_file_id" in id_schema["required"]
- assert id_schema["properties"]["client_file_id"]["type"] == "string"
+ id_schema = spec["components"]["schemas"]["TaskFileDetail"]
+ assert "file_id" in id_schema["required"]
+ assert id_schema["properties"]["file_id"]["type"] == "string"
assert set(spec["components"]["schemas"]["TaskUploadLink"]["properties"]) == {"url", "headers", "expires_at"}
if hasattr(app.state, "job_store"):
metadata_schema = spec["components"]["schemas"]["FileObjectModel"]
assert "file_name" in metadata_schema["required"]
assert "filename" not in metadata_schema["properties"]
- 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"]
+ assert "result_url" not in spec["components"]["schemas"]["TaskDetailResponse"]["properties"]
+ assert "result_url" in spec["components"]["schemas"]["TaskFileDetail"]["properties"]
+ assert "output_files" not in spec["components"]["schemas"]["TaskFileDetail"]["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
- ("identities", "expected_ids"),
- [
- ([{}, {}], ["f1", "f2"]),
- ([{"client_file_id": None}, {}], ["f1", "f2"]),
- ([{}, {"client_file_id": "f2"}, {}], ["f1", "f2", "f3"]),
- ([{}, {"client_file_id": "f1"}, {}], ["f2", "f1", "f3"]),
- ([{"client_file_id": "custom"}, {"client_file_id": "other"}], ["custom", "other"]),
- ],
-)
-def test_optional_file_ids_survive_upload_and_router_forwarding(
- service: tuple[TestClient, FastAPI], identities: list[dict[str, str | None]], expected_ids: list[str]
-) -> None:
- """缺省标识避让后续显式项,同名输入在重复查询、上传重试和 Router 转发后仍保持关联。"""
[email protected]("count", [1, 2, 3])
+def test_server_file_ids_survive_upload_and_router_forwarding(service: tuple[TestClient, FastAPI], count: int) -> None:
+ """每个同名输入在创建时获得不同 ID,查询与产物沿用本层公共 ID。"""
client, app = service
- response = client.post(
- "/v1/tasks",
- json={"files": [{"file_name": "same.html", "bytes": len(HTML), **identity} for identity in identities]},
- )
- assert response.status_code == 202, response.text
- task = response.json()
- for _ in range(2):
- assert [item["client_file_id"] for item in task["files"]] == expected_ids
- assert [item["client_file_id"] for item in pending_files(task)] == expected_ids
- assert all(item["file_name"] == "same.html" and "filename" not in item for item in task["files"])
- task = client.get(task_url(client, task)).json()
- for link in pending_files(task):
- for _ in range(2):
- assert client.put(link["upload"]["url"], content=HTML, headers=link["upload"]["headers"]).status_code == 200
+ inputs = [("same.html", HTML)] * count
+ task = _submit(client, inputs, hashes=False)
+ expected_ids = [item["file_id"] for item in task["files"]]
+ assert len(set(expected_ids)) == count and all(value.startswith("file-") for value in expected_ids)
+ _upload(client, task, inputs)
completed = _terminal(client, task)
- assert completed["status"] == "completed", completed
- assert [item["client_file_id"] for item in completed["files"]] == expected_ids
- assert _job_count(app) == len(expected_ids)
- for index in range(len(expected_ids)):
- assert b"Preserved content" in _archive(client, completed, index)["markdown.md"]
+ assert [item["file_id"] for item in completed["files"]] == expected_ids
+ assert all(item["result_url"].endswith(f"/{item['file_id']}/content") for item in completed["files"])
if hasattr(app.state, "test_transport"):
- forwarded = [
- item.client_file_id
- for worker in _execution_apps(app)
+ worker_ids = {
+ item.file_id
+ for worker in app.state.test_transport.apps.values()
for record in worker.state.task_store._records.values()
for item in record.inputs
- ]
- assert sorted(forwarded) == sorted(expected_ids)
+ }
+ assert len(worker_ids) == count and worker_ids.isdisjoint(expected_ids)
[email protected]("client_file_id", ["", "with space", "bad/id", "x" * 65, 123, False])
-def test_invalid_explicit_file_ids_fail_before_creation(service: tuple[TestClient, FastAPI], client_file_id: object) -> None:
[email protected]("file_id", ["", "with space", "bad/id", "x" * 65, 123, False])
+def test_invalid_explicit_file_ids_fail_before_creation(service: tuple[TestClient, FastAPI], file_id: object) -> None:
"""可选标识不放宽显式值校验,错误仍定位到新 files 字段且不创建任务。"""
client, app = service
- response = client.post(
- "/v1/tasks", json={"files": [{"file_name": "a.html", "bytes": len(HTML), "client_file_id": client_file_id}]}
- )
+ response = client.post("/v1/tasks", json={"files": [{"file_name": "a.html", "bytes": len(HTML), "file_id": file_id}]})
assert response.status_code == 400
- assert response.json()["error"]["param"] == "files.0.client_file_id"
+ assert response.json().get("error")["param"] == "files.0.file_id"
assert not app.state.task_store._records and _job_count(app) == 0
@@ -615,7 +592,7 @@ def test_files_metadata_and_attachment_keep_logical_names(service: tuple[TestCli
completed = _terminal(client, task)
item = completed["files"][0]
assert item["file_name"] == "report.v2.html" and "name" not in item and "filename" not in item
- result = client.get(item["result_url"].removesuffix("/content")).json()
+ result = client.get(item.get("result_url").removesuffix("/content")).json()
if hasattr(app.state, "file_store"):
source_id = next(iter(_source_references(app, completed)))
source = client.get(f"/v1/files/{source_id}").json()
@@ -624,11 +601,11 @@ def test_files_metadata_and_attachment_keep_logical_names(service: tuple[TestCli
else:
assert all(route.metadata["payload"]["purpose"] == "parse_output" for route in app.state.registry.list("file"))
assert result["file_name"] == "report.v2.zip" and "filename" not in result
- assert set(item["parse"]) == {"tier", "duration_ms", "parser_version"}
- assert item["parse"]["tier"] == "flash" and "tier" not in completed
+ assert set(item.get("parse")) == {"tier", "duration_ms", "parser_version"}
+ assert item.get("parse")["tier"] == "flash" and "tier" not in completed
assert pending_files(completed) == []
assert "uploads" not in completed and "include_model_output" not in completed
- download = client.get(item["result_url"])
+ download = client.get(item.get("result_url"))
assert download.status_code == 200
assert download.headers["content-disposition"] == 'attachment; filename="report.v2.zip"'
@@ -642,7 +619,6 @@ def test_files_metadata_and_attachment_keep_logical_names(service: tuple[TestCli
{"sha256sum": hashlib.sha256(HTML).hexdigest()},
{"bytes": len(HTML), "sha256sum": hashlib.sha256(HTML).hexdigest()},
{"url": "https://source.example/opaque?signature=" + "a" * 3000},
- {"client_file_id": None},
],
)
def test_url_inputs_download_in_worker_and_report_actual_metadata(
@@ -656,21 +632,21 @@ def test_url_inputs_download_in_worker_and_report_actual_metadata(
response = client.post("/v1/tasks", json={"files": [item]})
assert response.status_code == 202, response.text
task = response.json()
- expected_id = item["client_file_id"] or "f1"
- assert task["files"][0]["client_file_id"] == expected_id
+ expected_id = task["files"][0]["file_id"]
+ assert task["files"][0]["file_id"] == expected_id
assert task["status"] == "waiting-file" and pending_files(task) == []
- assert task["files"][0]["bytes"] == metadata.get("bytes")
- assert task["files"][0]["status"] == "waiting-file" and task["files"][0]["upload"] is None
+ assert "bytes" not in task["files"][0]
+ assert task["files"][0]["status"] == "waiting-file" and task["files"][0].get("upload") is None
result = _terminal(client, task)
assert result["status"] == "completed"
file = result["files"][0]
- assert file["client_file_id"] == expected_id
+ assert file["file_id"] == expected_id
assert file["file_name"] == "logical.html" and "name" not in file
- assert file["bytes"] == len(HTML) and "sha256sum" not in file
- assert file["status"] == "completed" and "file_id" not in file and file["upload"] is None
- assert file["url"] == item["url"]
+ assert file.get("bytes") == len(HTML) and "sha256sum" not in file
+ assert file["status"] == "completed" and "client_file_id" not in file and file.get("upload") is None
+ assert file.get("url") == item.get("url")
assert b"Preserved content" in _archive(client, result)["markdown.md"]
- assert len(url_downloads) == 1 and str(url_downloads[0].url) == item["url"]
+ assert len(url_downloads) == 1 and str(url_downloads[0].url) == item.get("url")
assert url_downloads[0].method == "GET" and "authorization" not in url_downloads[0].headers
assert client.put(f"/v1/tasks/{task['task_id']}/uploads/{expected_id}", content=HTML).status_code == 400
if hasattr(app.state, "test_transport"):
@@ -682,8 +658,8 @@ def test_url_manifest_validation(service: tuple[TestClient, FastAPI], url_downlo
"""大小只对 URL 可选,非法 URL、非正整数字节数及混合直传在接单前拒绝。"""
client, app = service
invalid = [
- {"client_file_id": "f1", "file_name": "a.html"},
- {"client_file_id": "f1", "file_name": "a.html", "bytes": None},
+ {"file_name": "a.html"},
+ {"file_name": "a.html", "bytes": None},
*[_url_manifest(url=value) for value in ("", "file:///tmp/a.html", "https://", "ftp://source/a.html")],
*[_url_manifest(bytes=value) for value in (0, -1, True, "10", 10.5)],
]
@@ -694,7 +670,7 @@ def test_url_manifest_validation(service: tuple[TestClient, FastAPI], url_downlo
assert response.status_code == 415
assert _job_count(app) == 0 and url_downloads == []
schema = client.get("/openapi.json").json()
- assert "upload_status" not in schema["components"]["schemas"]["TaskFileStatus"]["properties"]
+ assert "upload_status" not in schema["components"]["schemas"]["TaskFileDetail"]["properties"]
def test_mixed_url_upload_partial_and_no_early_reservation(
@@ -704,24 +680,24 @@ def test_mixed_url_upload_partial_and_no_early_reservation(
client, app = service
manifest = [
_url_manifest(file_name="same.html"),
- {"client_file_id": "local", "file_name": "same.html", "bytes": len(SECOND)},
- _url_manifest(client_file_id="bad", url="https://source.example/missing"),
+ {"file_name": "same.html", "bytes": len(SECOND)},
+ _url_manifest(url="https://source.example/missing"),
]
response = client.post("/v1/tasks", json={"files": manifest})
assert response.status_code == 202, response.text
task = response.json()
assert task["status"] == "waiting-file"
- assert [link["client_file_id"] for link in pending_files(task)] == ["local"]
+ assert [link["file_id"] for link in pending_files(task)] == [task["files"][1]["file_id"]]
ready = _file_done(client, task, 0)
assert b"Preserved content" in _archive(client, ready)["markdown.md"]
assert ready["files"][1]["status"] == "waiting-file"
- assert client.put(pending_files(task)[0]["upload"]["url"], content=SECOND).status_code == 200
+ assert client.put(pending_files(task)[0].get("upload").get("url"), content=SECOND).status_code == 200
result = _terminal(client, task)
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]["result_url"] is None
+ assert result["files"][0].get("bytes") == len(HTML)
+ assert result["files"][2].get("error") and result["files"][2].get("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 [item["file_id"] for item in result["files"]] == [item["file_id"] for item in task["files"]]
assert _job_count(app) == 3
@@ -742,9 +718,9 @@ def test_url_download_failures_are_per_file(
response = client.post("/v1/tasks", json={"files": [_url_manifest(**metadata)]})
assert response.status_code == 202
result = _terminal(client, response.json())
- 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 result["status"] == "failed" and result["files"][0].get("result_url") is None
+ assert result["files"][0]["status"] == "failed" and result["files"][0].get("error")["code"] == code
+ assert result["files"][0].get("bytes") == metadata.get("bytes")
assert len(url_downloads) == 1
@@ -782,7 +758,7 @@ def test_url_download_obeys_worker_policy_and_limit(
response = client.post("/v1/tasks", json={"files": [item]})
result = _terminal(client, response.json())
assert result["status"] == "failed"
- assert "max_url_bytes" in result["files"][0]["error"]["message"]
+ assert "max_url_bytes" in result["files"][0].get("error")["message"]
assert url_downloads[0].extensions["timeout"]["read"] == 7
for worker in _execution_apps(app):
worker.state.max_url_bytes = len(HTML)
@@ -807,7 +783,7 @@ def test_url_html_preserves_source_context(
response = client.post("/v1/tasks", json={"files": [_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"]
+ assert contexts[0].source_uri == _url_manifest().get("url")
assert contexts[0].transport_encoding == "utf-8"
assert contexts[0].local_resource_root is None
@@ -869,7 +845,7 @@ def test_cancel_url_download_closes_stream_and_releases_worker(
task = response.json()
assert started.wait(5)
before = time.monotonic()
- canceled = client.delete(task_url(client, task))
+ canceled = client.post(task_url(client, task) + "/cancel")
assert canceled.status_code == 200 and canceled.json()["status"] == "canceled"
assert time.monotonic() - before < 2
assert closed.wait(5)
@@ -882,8 +858,8 @@ 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_url(client, task)).json()
- assert final["status"] == "canceled" and final["files"][0]["result_url"] is None
- assert final["files"][0]["bytes"] is None
+ assert final["status"] == "canceled" and final["files"][0].get("result_url") is None
+ assert final["files"][0].get("bytes") is None
def test_router_private_hash_cache_and_task_scope(tmp_path: Path) -> None:
@@ -899,10 +875,10 @@ 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_url(client, task), headers=stranger).status_code == 404
- assert client.get(result["files"][0]["result_url"], headers=stranger).status_code == 404
+ assert client.get(result["files"][0].get("result_url"), headers=stranger).status_code == 404
other = _submit(client, [("a.html", HTML)], headers=stranger)
assert len(pending_files(other)) == 1
- assert client.delete(task_url(client, other), headers=stranger).status_code == 200
+ assert client.post(task_url(client, other) + "/cancel", headers=stranger).status_code == 200
owned = _submit(client, [("a.html", HTML)], headers=owner)
assert not pending_files(owned)
assert _terminal(client, owned, headers=owner)["status"] == "completed"
@@ -915,14 +891,14 @@ def test_task_links_respect_proxy_root(tmp_path: Path, root: str) -> None:
with TestClient(
app, base_url="http://testserver" + root, root_path=root, headers={"Authorization": "Bearer secret"}
) as client:
- manifest = [{"client_file_id": "f1", "file_name": "a.html", "bytes": len(HTML)}]
+ manifest = [{"file_name": "a.html", "bytes": len(HTML)}]
response = client.post("/v1/tasks", json={"files": manifest, "tier": "flash"})
assert response.status_code == 202
task = response.json()
assert task_url(client, task).startswith("http://testserver" + root + "/v1/tasks/")
_upload(client, task, [("a.html", HTML)])
result = _terminal(client, task)
- assert result["files"][0]["result_url"].startswith("http://testserver" + root + "/v1/files/")
+ assert result["files"][0].get("result_url").startswith("http://testserver" + root + "/v1/files/")
assert "markdown.md" in _archive(client, result)
@@ -934,9 +910,9 @@ def test_inflight_upload_may_finish_after_deadline(service: tuple[TestClient, Fa
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 = pending_files(task)[0]["upload"]["expires_at"]
+ expires_at = pending_files(task)[0].get("upload")["expires_at"]
assert 3598 <= expires_at - time.time() <= 3600
- assert pending_files(client.get(task_url(client, task)).json())[0]["upload"]["expires_at"] == expires_at
+ assert pending_files(client.get(task_url(client, task)).json())[0].get("upload")["expires_at"] == expires_at
async def cross_deadline() -> httpx.Response:
"""让真实 ASGI 上传跨过时限,并在受理流中途并发查询和尝试新 PUT。"""
@@ -951,25 +927,25 @@ def test_inflight_upload_may_finish_after_deadline(service: tuple[TestClient, Fa
assert state["files"][0]["status"] == "waiting-file"
assert state["files"][1]["status"] == "failed"
assert pending_files(state) == []
- rejected = await transport.put(pending_files(task)[1]["upload"]["url"], content=SECOND)
+ rejected = await transport.put(pending_files(task)[1].get("upload").get("url"), content=SECOND)
assert rejected.status_code == 410
if interrupted:
raise ClientDisconnect
yield HTML[10:]
- return await transport.put(pending_files(task)[0]["upload"]["url"], content=body())
+ return await transport.put(pending_files(task)[0].get("upload").get("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"])
+ assert all(file.get("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(pending_files(task)[0]["upload"]["url"], content=HTML).status_code == 410
+ assert client.put(pending_files(task)[0].get("upload").get("url"), content=HTML).status_code == 410
def test_expired_upload_rejects_before_reading_body(service: tuple[TestClient, FastAPI]) -> None:
@@ -977,13 +953,13 @@ def test_expired_upload_rejects_before_reading_body(service: tuple[TestClient, F
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(pending_files(task)[0]["upload"]["url"], content=_UnreadableBody())
- assert response.status_code == 410 and response.json()["error"]["code"] == "upload_expired"
+ response = client.put(pending_files(task)[0].get("upload").get("url"), content=_UnreadableBody())
+ assert response.status_code == 410 and response.json().get("error")["code"] == "upload_expired"
for _ in range(2):
state = client.get(task_url(client, task)).json()
assert state["status"] == "failed" and pending_files(state) == []
assert state["files"][0]["status"] == "failed"
- assert state["files"][0]["error"]["code"] == "upload_expired"
+ assert state["files"][0].get("error")["code"] == "upload_expired"
assert _job_count(app) == 0
@@ -998,16 +974,16 @@ def test_completed_child_retention_starts_after_parent_finishes(service: tuple[T
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(pending_files(task)[0]["upload"]["url"], content=HTML).status_code == 200
+ assert client.put(pending_files(task)[0].get("upload").get("url"), content=HTML).status_code == 200
ready = _file_done(client, task, 0)
- result_url = ready["files"][0]["result_url"]
+ result_url = ready["files"][0].get("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_url(client, task)).json()["files"][0]["status"] == "completed"
assert client.get(result_url).status_code == 200
- assert client.put(pending_files(task)[1]["upload"]["url"], content=SECOND).status_code == 200
+ assert client.put(pending_files(task)[1].get("upload").get("url"), content=SECOND).status_code == 200
assert _terminal(client, task)["status"] == "completed"
record = app.state.task_store._records[task["task_id"]]
@@ -1041,9 +1017,7 @@ def test_router_batch_uses_independent_workers_and_task_capabilities(tmp_path: P
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={"files": [{"client_file_id": "f1", "file_name": "a.html", "bytes": len(HTML)}]}
- )
+ response = client.post("/v1/tasks", json={"files": [{"file_name": "a.html", "bytes": len(HTML)}]})
assert response.status_code == 503
assert all(worker.active_jobs == 0 for worker in app.state.worker_pool.workers)
@@ -1066,7 +1040,9 @@ def test_worker_upload_renews_result_lease_after_long_transfer(tmp_path: Path) -
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") as transport:
response = await transport.put(
- pending_files(task)[0]["upload"]["url"], content=content(), headers={"x-mineru-task-lease-seconds": "120"}
+ pending_files(task)[0].get("upload").get("url"),
+ content=content(),
+ headers={"x-mineru-task-lease-seconds": "120"},
)
assert response.status_code == 200
assert record.lease_expires_at > time.time() + 110
@@ -1074,7 +1050,7 @@ def test_worker_upload_renews_result_lease_after_long_transfer(tmp_path: Path) -
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(result["files"][0].get("result_url")).status_code == 200
assert client.get(task_url(client, task), headers={"x-mineru-task-lease-seconds": "0"}).status_code == 200
@@ -1115,7 +1091,7 @@ def test_router_ends_local_result_lease_even_if_worker_rejects_release(tmp_path:
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"]
+ assert result["files"][0].get("result_url")
def test_removed_lists_preserve_task_creation_query_and_cancel(service: tuple[TestClient, FastAPI]) -> None:
@@ -1126,10 +1102,10 @@ def test_removed_lists_preserve_task_creation_query_and_cancel(service: tuple[Te
assert client.get("/v1/files").status_code == 404
assert "uploads" not in task and "include_model_output" not in task
assert {"tier", "status_url", "pending_uploads"}.isdisjoint(task)
- assert set(pending_files(task)[0]["upload"]) == {"url", "headers", "expires_at"}
- assert "/uploads/" in pending_files(task)[0]["upload"]["url"]
+ assert set(pending_files(task)[0].get("upload")) == {"url", "headers", "expires_at"}
+ assert "/uploads/" in pending_files(task)[0].get("upload").get("url")
assert pending_files(client.get(task_url(client, task)).json()) == pending_files(task)
- canceled = client.delete(task_url(client, task))
+ canceled = client.post(task_url(client, task) + "/cancel")
assert canceled.status_code == 200
assert canceled.json()["status"] == "canceled" and pending_files(canceled.json()) == []
@@ -1158,11 +1134,11 @@ def test_tasks_only_routes_and_health(service: tuple[TestClient, FastAPI]) -> No
assert "get" not in schema["paths"]["/v1/tasks"]
assert "/v1/files" not in schema["paths"]
assert {"TaskListItem", "TaskListResponse", "FileListResponse"}.isdisjoint(schema["components"]["schemas"])
- status_properties = schema["components"]["schemas"]["TaskStatusResponse"]["properties"]
+ status_properties = schema["components"]["schemas"]["TaskDetailResponse"]["properties"]
assert {"status_url", "tier", "pending_uploads", "uploads", "include_model_output"}.isdisjoint(status_properties)
- file_properties = schema["components"]["schemas"]["TaskFileStatus"]["properties"]
- assert {"sha256sum", "page_range", "file_id", "name", "upload_status"}.isdisjoint(file_properties)
- assert "upload" in schema["components"]["schemas"]["TaskFileStatus"]["required"]
+ file_properties = schema["components"]["schemas"]["TaskFileDetail"]["properties"]
+ assert {"sha256sum", "page_range", "client_file_id", "name", "upload_status"}.isdisjoint(file_properties)
+ assert "upload" not in schema["components"]["schemas"]["TaskFileDetail"]["required"]
assert "upload_method" not in schema["components"]["schemas"]["TaskUploadLink"]["properties"]
@@ -1183,7 +1159,7 @@ def test_removed_model_output_option_is_rejected(
},
)
assert response.status_code == 400
- assert response.json()["error"]["param"] == "include_model_output"
+ assert response.json().get("error")["param"] == "include_model_output"
assert not app.state.task_store._records and _job_count(app) == 0
@@ -1254,4 +1230,4 @@ def test_router_lease_timeout_does_not_expire_other_worker_results(tmp_path: Pat
client.portal.call(check_renewal)
assert client.get(task_url(client, result)).json()["status"] == "completed"
- assert client.get(result["files"][0]["result_url"]).status_code == 200
+ assert client.get(result["files"][0].get("result_url")).status_code == 200
diff --git a/tests/unittest/test_task_file_states.py b/tests/unittest/test_task_file_states.py
index 45601f13..c112538c 100644
--- a/tests/unittest/test_task_file_states.py
+++ b/tests/unittest/test_task_file_states.py
@@ -39,7 +39,7 @@ def _url_task(client: TestClient, name: str = "remote") -> dict[str, Any]:
assert response.status_code == 202, response.text
task = response.json()
assert task["status"] == "waiting-file"
- assert task["files"][0]["upload"] is None and "upload_status" not in task["files"][0]
+ assert task["files"][0].get("upload") is None and "upload_status" not in task["files"][0]
return task
@@ -72,20 +72,20 @@ def test_url_preparation_does_not_block_ready_files_or_use_upload_expiry(
assert started.wait(3)
app.state.task_store._records[remote["task_id"]].expires_at = 0
snapshot = client.get(task_url(client, remote)).json()
- assert snapshot["status"] == "waiting-file" and snapshot["files"][0]["error"] is None
- assert snapshot["files"][0]["parse"] is None
+ assert snapshot["status"] == "waiting-file" and snapshot["files"][0].get("error") is None
+ assert snapshot["files"][0].get("parse") is None
local = _submit(client, [("local.html", HTML)])
_upload(client, local, [("local.html", HTML)])
assert _terminal(client, local)["status"] == "completed"
assert not release.is_set()
if cancel:
- assert client.delete(task_url(client, remote)).json()["status"] == "canceled"
+ assert client.post(task_url(client, remote) + "/cancel").json()["status"] == "canceled"
assert closed.wait(3)
else:
release.set()
completed = _terminal(client, remote)
assert completed["status"] == "completed"
- assert completed["files"][0]["bytes"] == len(HTML)
+ assert completed["files"][0].get("bytes") == len(HTML)
assert b"Preserved content" in _archive(client, completed)["markdown.md"]
assert all(not job.prepared_sources for job in app.state.job_store._jobs.values())
finally:
@@ -135,7 +135,7 @@ def test_ready_url_inputs_wait_in_pending_with_bounded_preparation(
assert client.get(task_url(client, third)).json()["status"] == "waiting-file"
assert downloads == ["/second"]
if cancel_ready:
- assert client.delete(task_url(client, second)).json()["status"] == "canceled"
+ assert client.post(task_url(client, second) + "/cancel").json()["status"] == "canceled"
deadline = time.monotonic() + 3
while "/third" not in downloads:
assert time.monotonic() < deadline
@@ -178,4 +178,4 @@ def test_file_duration_includes_preparation_but_excludes_queue_wait(tmp_path: Pa
clock[0] += 1000
client.portal.call(app.state.job_store._semaphore.release)
result = _terminal(client, task)
- assert result["files"][0]["parse"]["duration_ms"] == 5000
+ assert result["files"][0].get("parse")["duration_ms"] == 5000
diff --git a/tests/unittest/test_task_http.py b/tests/unittest/test_task_http.py
index 55227040..e17b6272 100644
--- a/tests/unittest/test_task_http.py
+++ b/tests/unittest/test_task_http.py
@@ -135,12 +135,11 @@ def _submit(client: httpx.Client, files: list[tuple[str, bytes]], *, hashes: boo
"""以 JSON 提交文件清单,hash 缺省时不放入任何替代标识。"""
manifest = [
{
- "client_file_id": f"f{index + 1}",
"file_name": name,
"bytes": len(data),
**({"sha256sum": hashlib.sha256(data).hexdigest()} if hashes else {}),
}
- for index, (name, data) in enumerate(files)
+ for name, data in files
]
response = client.post("/v1/tasks", json={"files": manifest, "tier": "flash", "ocr_mode": "txt", **options})
assert response.status_code == 202, response.text
@@ -156,7 +155,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 all(file["result_url"] is None for file in payload["files"] if file["status"] != "completed")
+ assert all(file.get("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")
@@ -167,7 +166,7 @@ def _members(data: bytes) -> dict[str, bytes]:
return {name: archive.read(name) for name in archive.namelist()}
-def test_pdf_without_client_id_keeps_metadata_and_cached_results(live_service: _LiveService, tmp_path: Path) -> None:
+def test_pdf_without_file_id_keeps_metadata_and_cached_results(live_service: _LiveService, tmp_path: Path) -> None:
"""真实 TCP 上传 PDF,确认自动标识、Files 元数据、附件命名及缓存命中后的正文均正确。"""
from reportlab.pdfgen.canvas import Canvas
@@ -187,18 +186,21 @@ def test_pdf_without_client_id_keeps_metadata_and_cached_results(live_service: _
response = client.post("/v1/tasks", json=payload)
assert response.status_code == 202, response.text
task = response.json()
- assert task["files"][0]["client_file_id"] == pending_files(task)[0]["client_file_id"] == "f1"
+ assert task["files"][0]["file_id"] == pending_files(task)[0]["file_id"]
+ assert task["files"][0]["file_id"].startswith("file-")
link = pending_files(task)[0]
for _ in range(2):
- upload = client.put(link["upload"]["url"], content=data, headers=link["upload"]["headers"])
+ upload = client.put(link.get("upload").get("url"), content=data, headers=link.get("upload")["headers"])
assert upload.status_code == 200, upload.text
completed = _wait(client, task)
assert completed["status"] == "completed", completed
item = completed["files"][0]
- assert item["client_file_id"] == "f1" and item["file_name"] == "report.v2.pdf" and "filename" not in item
- result = client.get(item["result_url"].removesuffix("/content"))
+ assert (
+ item["file_id"] == task["files"][0]["file_id"] and item["file_name"] == "report.v2.pdf" and "filename" not in item
+ )
+ result = client.get(item.get("result_url").removesuffix("/content"))
assert result.status_code == 200 and result.json()["file_name"] == "report.v2.zip"
- download = client.get(item["result_url"])
+ download = client.get(item.get("result_url"))
assert download.status_code == 200
assert download.headers["content-disposition"] == 'attachment; filename="report.v2.zip"'
(tmp_path / "report.v2.zip").write_bytes(download.content)
@@ -209,11 +211,11 @@ def test_pdf_without_client_id_keeps_metadata_and_cached_results(live_service: _
cached = client.post("/v1/tasks", json=payload)
assert cached.status_code == 202, cached.text
cached_task = cached.json()
- assert pending_files(cached_task) == [] and cached_task["files"][0]["client_file_id"] == "f1"
- assert cached_task["files"][0]["status"] == "pending" and cached_task["files"][0]["upload"] is None
+ assert pending_files(cached_task) == [] and cached_task["files"][0]["file_id"] != task["files"][0]["file_id"]
+ assert cached_task["files"][0]["status"] == "pending" and cached_task["files"][0].get("upload") is None
cached_result = _wait(client, cached_task)
assert cached_result["status"] == "completed", cached_result
- cached_download = client.get(cached_result["files"][0]["result_url"])
+ cached_download = client.get(cached_result["files"][0].get("result_url"))
assert cached_download.status_code == 200
assert _members(cached_download.content)["markdown.md"] == members["markdown.md"]
@@ -250,11 +252,11 @@ def test_router_keeps_tls_proxy_headers_on_the_public_hop_only(tmp_path: Path) -
for index in range(2):
task = _submit(client, [(f"document-{index}.html", HTML)])
assert "status_url" not in task
- assert all(urlsplit(item["upload"]["url"]).scheme == "https" for item in pending_files(task))
+ assert all(urlsplit(item.get("upload").get("url")).scheme == "https" for item in pending_files(task))
assert len(pending_files(task)) == (1 if index == 0 else 0)
for upload in pending_files(task):
# 以本地 HTTP 模拟 TLS 终止代理到 Router 的后段连接,保留真实入站代理头。
- response = client.put(urlsplit(upload["upload"]["url"]).path, content=HTML)
+ response = client.put(urlsplit(upload.get("upload").get("url")).path, content=HTML)
assert response.status_code == 200, response.text
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
@@ -267,7 +269,7 @@ def test_router_keeps_tls_proxy_headers_on_the_public_hop_only(tmp_path: Path) -
else:
pytest.fail("Task did not finish through the TLS proxy hop")
assert result["status"] == "completed", result
- result_url = result["files"][0]["result_url"]
+ result_url = result["files"][0].get("result_url")
assert urlsplit(result_url).scheme == "https"
response = client.get(urlsplit(result_url).path)
assert response.status_code == 200, response.text
@@ -329,9 +331,9 @@ def test_documented_client_script(live_service: _LiveService, tmp_path: Path, fo
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
- for index, path in enumerate(paths):
+ for path in paths:
extension = formats if formats in {"html", "docx"} else "zip"
- output = tmp_path / "results" / f"f{index + 1}" / (path.stem + "." + extension)
+ output = next((tmp_path / "results").glob(f"*/{path.stem}.{extension}"))
assert output.is_file()
if extension == "zip":
assert "中文内容".encode() in _members(output.read_bytes())["markdown.md"]
@@ -345,16 +347,16 @@ def test_hash_preflight_sends_only_missing_file_bytes(live_service: _LiveService
"""真实网络计数证明混合命中仅上传缺失文件,全命中不发送任何文件 PUT。"""
with _client(live_service) as client:
first = _submit(client, [("a.html", HTML)])
- assert client.put(pending_files(first)[0]["upload"]["url"], content=HTML).status_code == 200
+ assert client.put(pending_files(first)[0].get("upload").get("url"), content=HTML).status_code == 200
assert _wait(client, first)["status"] == "completed"
second_data = b"<h1>second</h1>"
mixed = _submit(client, [("renamed.html", HTML), ("b.html", second_data)])
- assert [link["client_file_id"] for link in pending_files(mixed)] == ["f2"]
- assert client.put(pending_files(mixed)[0]["upload"]["url"], content=second_data).status_code == 200
+ assert [link["file_id"] for link in pending_files(mixed)] == [mixed["files"][1]["file_id"]]
+ assert client.put(pending_files(mixed)[0].get("upload").get("url"), content=second_data).status_code == 200
assert _wait(client, mixed)["status"] == "completed"
base = f"/v1/tasks/{mixed['task_id']}/uploads/"
- assert live_service.counts.get(base + "f1", 0) == 0
- assert live_service.counts[base + "f2"] == len(second_data)
+ assert live_service.counts.get(base + mixed["files"][0]["file_id"], 0) == 0
+ assert live_service.counts[base + mixed["files"][1]["file_id"]] == len(second_data)
hit = _submit(client, [("a.html", HTML), ("b.html", second_data)])
assert pending_files(hit) == []
assert _wait(client, hit)["status"] == "completed"
@@ -364,7 +366,7 @@ def test_hash_preflight_sends_only_missing_file_bytes(live_service: _LiveService
headers={"Authorization": "Bearer wrong"},
json={
"files": [
- {"client_file_id": "f1", "file_name": "a.html", "bytes": len(HTML)},
+ {"file_name": "a.html", "bytes": len(HTML)},
]
},
)
@@ -379,8 +381,8 @@ def test_disconnect_then_resume_keeps_uploaded_files(live_service: _LiveService,
second_path.write_bytes(second)
with _client(live_service) as client:
task = _submit(client, [(first_path.name, HTML), (second_path.name, second)])
- assert client.put(pending_files(task)[0]["upload"]["url"], content=HTML).status_code == 200
- target = urlsplit(pending_files(task)[1]["upload"]["url"])
+ assert client.put(pending_files(task)[0].get("upload").get("url"), content=HTML).status_code == 200
+ target = urlsplit(pending_files(task)[1].get("upload").get("url"))
connection = socket.create_connection((target.hostname, target.port), timeout=5)
prefix = second[:4096]
try:
@@ -401,10 +403,10 @@ def test_disconnect_then_resume_keeps_uploaded_files(live_service: _LiveService,
assert pending["files"][1]["status"] == "waiting-file"
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(pending_files(task)[0]["upload"]["url"]).path] == len(HTML)
+ assert live_service.counts[urlsplit(pending_files(task)[0].get("upload").get("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 / "results/f2/b.zip").read_bytes())
+ members = _members((tmp_path / "results" / task["files"][1]["file_id"] / "b.zip").read_bytes())
assert b"Resumed file" in members["markdown.md"]
final = client.get(task_url(client, task)).json()
assert final["task_id"] == task["task_id"] and final["status"] == "completed"
@@ -426,12 +428,12 @@ def test_cancel_response_does_not_wait_for_native_thread_cleanup(
try:
with _client(live_service) as client:
task = _submit(client, [("a.html", HTML)])
- assert client.put(pending_files(task)[0]["upload"]["url"], content=HTML).status_code == 200
+ assert client.put(pending_files(task)[0].get("upload").get("url"), content=HTML).status_code == 200
assert entered.wait(5)
- canceled = client.delete(task_url(client, task), timeout=2)
+ canceled = client.post(task_url(client, task) + "/cancel", timeout=2)
assert canceled.status_code == 200 and canceled.json()["status"] == "canceled"
assert not release.is_set()
- assert client.get(task_url(client, task)).json()["files"][0]["result_url"] is None
+ assert client.get(task_url(client, task)).json()["files"][0].get("result_url") is None
finally:
release.set()
@@ -456,19 +458,19 @@ def test_upload_over_200_mib_is_accepted(live_service: _LiveService, tmp_path: P
with _client(live_service) as client:
response = client.post(
"/v1/tasks",
- json={"tier": "flash", "files": [{"client_file_id": "large", "file_name": source.name, "bytes": size}]},
+ json={"tier": "flash", "files": [{"file_name": source.name, "bytes": size}]},
)
assert response.status_code == 202, response.text
task = response.json()
with source.open("rb") as stream:
uploaded = client.put(
- pending_files(task)[0]["upload"]["url"], content=stream, headers={"Content-Length": str(size)}
+ pending_files(task)[0].get("upload").get("url"), content=stream, headers={"Content-Length": str(size)}
)
assert uploaded.status_code == 200, uploaded.text
- assert live_service.counts[urlsplit(pending_files(task)[0]["upload"]["url"]).path] == size
+ assert live_service.counts[urlsplit(pending_files(task)[0].get("upload").get("url")).path] == size
assert started.wait(60)
assert client.get(task_url(client, task)).json()["files"][0]["status"] in {"pending", "running", "completed"}
- assert client.delete(task_url(client, task)).json()["status"] == "canceled"
+ assert client.post(task_url(client, task) + "/cancel").json()["status"] == "canceled"
@pytest.mark.parametrize("page_count", [601, 1001])
@@ -482,10 +484,10 @@ def test_large_page_count_pdf_is_not_rejected(live_service: _LiveService, page_c
data = buffer.getvalue()
with _client(live_service) as client:
task = _submit(client, [("many-pages.pdf", data)])
- assert client.put(pending_files(task)[0]["upload"]["url"], content=data).status_code == 200
+ assert client.put(pending_files(task)[0].get("upload").get("url"), content=data).status_code == 200
result = _wait(client, task, timeout=90)
assert result["status"] == "completed", result
- download = client.get(result["files"][0]["result_url"])
+ download = client.get(result["files"][0].get("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
@@ -518,10 +520,10 @@ def test_real_documents_match_local_parser_outputs(live_service: _LiveService, d
expected = build_task_output(baseline, ["default"], Path(directory) / "outputs").read_bytes()
with _client(live_service) as client:
task = _submit(client, [(name, data)], page_range=page_range, output_formats=["default"])
- assert client.put(pending_files(task)[0]["upload"]["url"], content=data).status_code == 200
+ assert client.put(pending_files(task)[0].get("upload").get("url"), content=data).status_code == 200
result = _wait(client, task)
assert result["status"] == "completed", result
- output = client.get(result["files"][0]["result_url"])
+ output = client.get(result["files"][0].get("result_url"))
assert output.status_code == 200
assert _members(output.content) == _members(expected)
@@ -563,7 +565,6 @@ def test_url_task_over_http_downloads_chunked_source(live_service: _LiveService,
for worker in live_service.execution_apps:
worker.state.allow_http_source = True
item = {
- "client_file_id": "url-1",
"file_name": f"logical.{document}",
"url": f"{source_server.url}/opaque?signature=a%2Fb&part=1",
**({"page_range": "2"} if document == "pdf" else {}),
@@ -583,9 +584,9 @@ def test_url_task_over_http_downloads_chunked_source(live_service: _LiveService,
assert pending_files(task) == [] and task["files"][0]["status"] == "waiting-file"
result = _wait(client, task)
assert result["status"] == "completed", result
- assert result["files"][0]["bytes"] == len(data)
+ assert result["files"][0].get("bytes") == len(data)
assert "sha256sum" not in result["files"][0]
- members = _members(client.get(result["files"][0]["result_url"]).content)
+ members = _members(client.get(result["files"][0].get("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"
@@ -596,13 +597,13 @@ def test_url_task_over_http_downloads_chunked_source(live_service: _LiveService,
assert response.status_code == 202, response.text
baseline_result = _wait(client, response.json())
assert baseline_result["status"] == "completed"
- baseline_url = baseline_result["files"][0]["result_url"]
+ baseline_url = baseline_result["files"][0].get("result_url")
else:
baseline = _submit(client, [(item["file_name"], data)], page_range="2")
- assert client.put(pending_files(baseline)[0]["upload"]["url"], content=data).status_code == 200
+ assert client.put(pending_files(baseline)[0].get("upload").get("url"), content=data).status_code == 200
baseline_result = _wait(client, baseline)
assert baseline_result["status"] == "completed"
- baseline_url = baseline_result["files"][0]["result_url"]
+ baseline_url = baseline_result["files"][0].get("result_url")
baseline_members = _members(client.get(baseline_url).content)
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/"}
@@ -639,29 +640,29 @@ class _CloudState:
ready, expired = record["ready"], record["expired"]
files = []
for index, item in enumerate(record["files"]):
- client_id = item["client_file_id"]
- status = "completed" if client_id in ready else "waiting-file"
- if client_id in expired:
+ file_id = item["file_id"]
+ status = "completed" if file_id in ready else "waiting-file"
+ if file_id in expired:
status = "failed"
- if client_id in ready and self.forced_status in {"failed", "running"}:
+ if file_id in ready and self.forced_status in {"failed", "running"}:
status = self.forced_status
- if self.forced_status == "partial" and index == len(record["files"]) - 1 and client_id in ready:
+ if self.forced_status == "partial" and index == len(record["files"]) - 1 and file_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']}"
+ result_url = f"{self.storage_url}/download/{task_id}/{file_id}?signature={record['download_version']}"
if self.api_download_redirect:
- result_url = f"{self.gateway_url}/redirect/{task_id}/{client_id}"
+ result_url = f"{self.gateway_url}/redirect/{task_id}/{file_id}"
files.append(
{
- "client_file_id": client_id,
+ "file_id": file_id,
"file_name": item["file_name"],
- "bytes": item["bytes"],
+ "bytes": item.get("bytes"),
"url": item.get("url"),
"upload": None
- if client_id in ready | expired
+ if file_id in ready | expired
else {
- "url": f"{self.storage_url}/objects/{task_id}/{client_id}?signature=0",
+ "url": f"{self.storage_url}/objects/{task_id}/{file_id}?signature=0",
"headers": {"Content-Type": "application/octet-stream", "X-Upload-Token": "storage-token"},
"expires_at": record["expires_at"],
},
@@ -683,8 +684,7 @@ class _CloudState:
payload = {
"task_id": task_id,
"status": status,
- "files": files,
- "error": None,
+ "files": [{key: value for key, value in item.items() if value is not None} for item in files],
"output_formats": record["output_formats"],
}
if self.invalid_response == "missing_id":
@@ -717,27 +717,40 @@ def _cloud_apps(state: _CloudState) -> tuple[FastAPI, FastAPI]:
submitted = await request.json()
manifest = submitted["files"]
task_id = f"cloud_{len(state.tasks) + 1}"
+ assert all({"client_file_id", "file_id"}.isdisjoint(item) for item in manifest)
+ manifest = [{**item, "file_id": f"file-{task_id}-{index + 1}"} for index, item in enumerate(manifest)]
state.tasks[task_id] = {
"files": manifest,
- "ready": {item["client_file_id"] for item in manifest if item.get("sha256sum") in state.cache},
+ "ready": {item["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)
+ detail = state.payload(task_id)
+ return JSONResponse(
+ {
+ "task_id": detail["task_id"],
+ "status": detail["status"],
+ "files": [
+ {key: value for key, value in item.items() if key in {"file_id", "file_name", "status", "upload"}}
+ for item in detail["files"]
+ ],
+ },
+ status_code=202,
+ )
@gateway.get("/v1/tasks/{task_id}")
async def get_task(task_id: str) -> Response:
"""仅返回元数据和 OSS 下载链接,不回源读取或代理 ZIP 内容。"""
return JSONResponse(state.payload(task_id))
- @gateway.get("/redirect/{task_id}/{client_file_id}")
- async def redirect(task_id: str, client_file_id: str) -> Response:
+ @gateway.get("/redirect/{task_id}/{file_id}")
+ async def redirect(task_id: str, file_id: str) -> Response:
"""模拟同源下载地址重定向到同主机不同端口,检查客户端凭据隔离。"""
return RedirectResponse(
- f"{state.storage_url}/download/{task_id}/{client_file_id}?signature={state.tasks[task_id]['download_version']}",
+ f"{state.storage_url}/download/{task_id}/{file_id}?signature={state.tasks[task_id]['download_version']}",
status_code=302,
)
@@ -748,33 +761,33 @@ def _cloud_apps(state: _CloudState) -> tuple[FastAPI, FastAPI]:
assert request.headers.get("authorization") is None
return await call_next(request)
- @storage.put("/objects/{task_id}/{client_file_id}")
- async def upload(task_id: str, client_file_id: str, request: Request) -> Response:
+ @storage.put("/objects/{task_id}/{file_id}")
+ async def upload(task_id: str, file_id: str, request: Request) -> Response:
"""只在对象存储接收文件字节,并模拟临时错误、链接过期和提交后响应丢失。"""
assert request.headers.get("x-upload-token") == "storage-token"
- key = task_id + "/" + client_file_id
+ key = task_id + "/" + file_id
state.upload_attempts[key] = state.upload_attempts.get(key, 0) + 1
record = state.tasks[task_id]
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["expired"].add(client_file_id)
+ record["expired"].add(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()
- item = next(item for item in record["files"] if item["client_file_id"] == client_file_id)
- assert len(data) == item["bytes"]
+ item = next(item for item in record["files"] if item["file_id"] == file_id)
+ assert len(data) == item.get("bytes")
actual = hashlib.sha256(data).hexdigest()
assert item.get("sha256sum") in {None, actual}
state.cache[actual] = data
- record["ready"].add(client_file_id)
+ record["ready"].add(file_id)
if state.lost_upload_response:
return Response(status_code=503)
return Response(status_code=200)
- @storage.get("/download/{task_id}/{client_file_id}")
- async def download(task_id: str, client_file_id: str, request: Request) -> Response:
+ @storage.get("/download/{task_id}/{file_id}")
+ async def download(task_id: str, file_id: str, request: Request) -> Response:
"""结果字节仅由对象存储返回;过期地址通过再次查询原任务刷新。"""
record = state.tasks[task_id]
if request.query_params.get("signature") != str(record["download_version"]):
@@ -784,7 +797,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("markdown.md", f"# OSS result {client_file_id}\n")
+ archive.writestr("markdown.md", f"# OSS result {file_id}\n")
return Response(output.getvalue(), media_type="application/zip")
return gateway, storage
@@ -825,7 +838,7 @@ 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 / "results/f1/a.zip").read_bytes())["markdown.md"] == b"# OSS result f1\n"
+ assert _members((tmp_path / "results/file-cloud_1-1/a.zip").read_bytes())["markdown.md"] == b"# OSS result file-cloud_1-1\n"
@pytest.mark.parametrize("failure", ["transient_upload", "lost_upload_response", "expired_download", "api_download_redirect"])
@@ -837,9 +850,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 == "transient_upload" else 1)
+ assert cloud.upload_attempts["cloud_1/file-cloud_1-1"] == (2 if failure == "transient_upload" else 1)
assert all(auth is None for surface, _, _, auth in cloud.requests if surface == "storage")
- assert (tmp_path / "results/f1/a.zip").is_file()
+ assert (tmp_path / "results/file-cloud_1-1/a.zip").is_file()
@pytest.mark.parametrize("invalid", ["missing_id", "unknown_status"])
@@ -852,7 +865,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 / "results/f1/a.zip").exists()
+ assert not (tmp_path / "results/file-cloud_1-1/a.zip").exists()
@pytest.mark.parametrize("status,exit_code", [("partial", 2), ("failed", 1), ("running", 124)])
@@ -866,7 +879,7 @@ def test_client_exit_codes_and_poll_budget(cloud: _CloudState, tmp_path: Path, s
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 / "results/f1/a.zip").exists() == (status == "partial")
+ assert (tmp_path / "results/file-cloud_1-1/a.zip").exists() == (status == "partial")
if status == "running":
assert "continues running" in result.stderr
@@ -878,8 +891,8 @@ def test_client_does_not_renew_expired_upload(cloud: _CloudState, tmp_path: Path
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()
+ assert len(cloud.tasks) == 1 and cloud.upload_attempts == {"cloud_1/file-cloud_1-1": 1}
+ assert not (tmp_path / "results/file-cloud_1-1/a.zip").exists()
@pytest.mark.parametrize("asynchronous", [False, True])
diff --git a/tests/unittest/test_task_outputs.py b/tests/unittest/test_task_outputs.py
index 8ed8c1c2..41561a85 100644
--- a/tests/unittest/test_task_outputs.py
+++ b/tests/unittest/test_task_outputs.py
@@ -123,7 +123,7 @@ def test_all_task_output_combinations(
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"])
+ downloaded = client.get(finished["files"][0].get("result_url"))
assert downloaded.status_code == 200
if formats == ["html"]:
assert downloaded.headers["content-type"].startswith("text/html")
@@ -173,7 +173,7 @@ def test_task_formats_use_only_service_authentication(tmp_path: Path, formats: l
"""启用 Key 时四种格式都需要服务认证,通过认证后都可执行。"""
app = api_server.create_app(upload_dir=str(tmp_path), tier="flash", api_key="secret")
with TestClient(app) as client:
- body = {"files": [{"client_file_id": "f1", "file_name": "a.html", "bytes": len(HTML)}], "output_formats": formats}
+ body = {"files": [{"file_name": "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)
@@ -188,7 +188,7 @@ def test_duplicate_formats_and_missing_images(service: tuple[TestClient, FastAPI
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")
+ assert client.get(completed["files"][0].get("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
@@ -203,5 +203,5 @@ def test_duplicate_formats_and_missing_images(service: tuple[TestClient, FastAPI
_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"
+ assert failed["files"][0].get("result_url") is None
+ assert failed["files"][0].get("error")["code"] == "result_packaging_failed"
diff --git a/tests/unittest/test_task_response_contract.py b/tests/unittest/test_task_response_contract.py
index 96d710a7..9398f185 100644
--- a/tests/unittest/test_task_response_contract.py
+++ b/tests/unittest/test_task_response_contract.py
@@ -93,29 +93,25 @@ def test_mixed_file_tiers_come_from_completed_results(
assert {"status_url", "tier", "pending_uploads"}.isdisjoint(task)
for item in task["files"]:
assert set(item) == {
- "client_file_id",
+ "file_id",
"file_name",
"bytes",
- "url",
"upload",
"status",
- "parse",
- "result_url",
- "error",
}
- assert item["parse"] is None
- assert set(item["upload"]) == {"url", "headers", "expires_at"}
+ assert item.get("parse") is None
+ assert set(item.get("upload")) == {"url", "headers", "expires_at"}
_upload(client, task, inputs)
completed = _terminal(client, task)
assert completed["status"] == "completed", completed
- assert [item["parse"]["tier"] for item in completed["files"]] == [actual, "flash", "flash", actual]
+ assert [item.get("parse")["tier"] for item in completed["files"]] == [actual, "flash", "flash", actual]
assert dict(calls) == {".pdf": requested, ".html": "flash", ".docx": "flash", ".png": requested}
for index, item in enumerate(completed["files"]):
- assert item["upload"] is None
- assert set(item["parse"]) == {"tier", "duration_ms", "parser_version"}
- assert item["parse"]["duration_ms"] >= 0
+ assert item.get("upload") is None
+ assert set(item.get("parse")) == {"tier", "duration_ms", "parser_version"}
+ assert item.get("parse")["duration_ms"] >= 0
middle = json.loads(_archive(client, completed, index)["middle_json.json"])
- assert middle["extensions"]["mineru"]["tier"] == item["parse"]["tier"]
+ assert middle["extensions"]["mineru"]["tier"] == item.get("parse")["tier"]
assert b"Mixed task HTML" in _archive(client, completed, 1)["markdown.md"]
assert b"Mixed task DOCX" in _archive(client, completed, 2)["markdown.md"]
@@ -136,4 +132,4 @@ def test_missing_actual_metadata_does_not_fabricate_requested_tier(tmp_path: Pat
_upload(client, task, inputs)
result = _terminal(client, task)
assert result["status"] == "failed"
- assert result["files"][0]["parse"] is None and result["files"][0]["result_url"] is None
+ assert result["files"][0].get("parse") is None and result["files"][0].get("result_url") is None
diff --git a/tests/unittest/test_task_split_responses.py b/tests/unittest/test_task_split_responses.py
new file mode 100644
index 00000000..4edad42c
--- /dev/null
+++ b/tests/unittest/test_task_split_responses.py
@@ -0,0 +1,249 @@
+"""验证独立响应、服务端公共文件 ID,以及取消后可直接使用的逐文件终态。"""
+
+from __future__ import annotations
+
+import hashlib
+import io
+import time
+import zipfile
+from pathlib import Path
+from typing import Any
+
+import httpx
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from test_task_api import HTML, SECOND
+from test_task_api import service as _service_fixture
+from mineru.parser.api_server import FileStore
+from mineru.kit.router.resources import ResourceRegistry
+
+
+service = _service_fixture
+
+
+def _create(client: TestClient, contents: list[bytes]) -> dict[str, Any]:
+ """用同名输入验证服务端按请求顺序分配 ID,不依赖文件名唯一性。"""
+ response = client.post(
+ "/v1/tasks",
+ json={
+ "files": [
+ {"file_name": "same.html", "bytes": len(content), "sha256sum": hashlib.sha256(content).hexdigest()}
+ for content in contents
+ ]
+ },
+ )
+ assert response.status_code == 202, response.text
+ return response.json()
+
+
+def _wait_files(client: TestClient, created: dict[str, Any], count: int) -> dict[str, Any]:
+ """等待指定数量的成功文件,允许同一父任务仍有尚未上传的输入。"""
+ deadline = time.monotonic() + 10
+ while time.monotonic() < deadline:
+ response = client.get(f"/v1/tasks/{created['task_id']}")
+ assert response.status_code == 200, response.text
+ task = response.json()
+ if sum(item["status"] == "completed" for item in task["files"]) == count:
+ return task
+ assert all(item["status"] != "failed" for item in task["files"]), task
+ time.sleep(0.01)
+ raise AssertionError(f"Files did not complete: {task}")
+
+
[email protected]("field", ["client_file_id", "file_id"])
[email protected]("value", [None, "file-user"])
+def test_creation_rejects_all_caller_file_ids(service: tuple[TestClient, FastAPI], field: str, value: str | None) -> None:
+ """客户端不能通过新旧字段注入标识,空值也不能绕过请求模型。"""
+ client, app = service
+ response = client.post("/v1/tasks", json={"files": [{"file_name": "x.html", "bytes": 1, field: value}]})
+ assert response.status_code == 400
+ assert response.json()["error"]["code"] == "invalid_request"
+ assert not app.state.task_store._records
+
+
+def test_split_responses_keep_ids_and_cancellation_results(service: tuple[TestClient, FastAPI]) -> None:
+ """完整 HTTP 链路验证预留 ID、独立回执、同名产物和取消后直接下载。"""
+ client, _app = service
+ contents = [HTML, SECOND, b"<p>not uploaded</p>"]
+ created = _create(client, contents)
+ assert set(created) == {"task_id", "status", "files"}
+ assert client.delete(f"/v1/tasks/{created['task_id']}").status_code == 405
+ assert client.get(f"/v1/tasks/{created['task_id']}").json()["status"] == "waiting-file"
+ file_ids = [item["file_id"] for item in created["files"]]
+ assert len(set(file_ids)) == 3 and all(value.startswith("file-") for value in file_ids)
+ for item in created["files"]:
+ assert set(item) == {"file_id", "file_name", "status", "upload"}
+ for suffix in ("", "/content"):
+ assert client.get(f"/v1/files/{item['file_id']}{suffix}").status_code == 404
+ assert client.delete(f"/v1/files/{item['file_id']}").status_code == 405
+ detail = client.get(f"/v1/tasks/{created['task_id']}").json()
+ assert detail["progress"] == {"completed": 0, "failed": 0, "total": 3}
+ assert {"started_at", "finished_at", "error"}.isdisjoint(detail)
+ for item, content in zip(created["files"][:2], contents):
+ response = client.put(item["upload"]["url"], content=content, headers=item["upload"]["headers"])
+ assert response.status_code == 200, response.text
+ assert set(response.json()) == {"task_id", "file_id", "status"}
+ assert response.json()["file_id"] == item["file_id"]
+ ready = _wait_files(client, created, 2)
+ assert [item["file_id"] for item in ready["files"]] == file_ids
+ response = client.post(f"/v1/tasks/{created['task_id']}" + "/cancel")
+ assert response.status_code == 200, response.text
+ canceled = response.json()
+ assert set(canceled) == {"task_id", "status", "finished_at", "files"}
+ assert canceled["status"] == "canceled"
+ assert [item["status"] for item in canceled["files"]] == ["completed", "completed", "canceled"]
+ assert [item["file_id"] for item in canceled["files"]] == file_ids
+ assert set(canceled["files"][2]) == {"file_id", "file_name", "status"}
+ for item in canceled["files"][:2]:
+ assert set(item) == {"file_id", "file_name", "status", "parse", "result_url"}
+ assert item["result_url"].endswith(f"/v1/files/{item['file_id']}/content")
+ metadata = client.get(f"/v1/files/{item['file_id']}").json()
+ assert metadata["id"] == item["file_id"] and metadata["file_name"] == "same.zip"
+ downloaded = client.get(item["result_url"])
+ assert downloaded.status_code == 200
+ with zipfile.ZipFile(io.BytesIO(downloaded.content)) as archive:
+ assert archive.read("markdown.md").strip()
+ assert client.post(f"/v1/tasks/{created['task_id']}" + "/cancel").status_code == 409
+ assert client.delete(f"/v1/files/{file_ids[0]}").status_code == 405
+ client.get(f"/v1/tasks/{created['task_id']}")
+ assert client.get(f"/v1/files/{file_ids[0]}").status_code == 200
+ assert client.get(canceled["files"][0]["result_url"]).status_code == 200
+ assert client.get(f"/v1/files/{file_ids[2]}").status_code == 404
+
+
+def test_cached_source_uses_new_public_result_id(service: tuple[TestClient, FastAPI]) -> None:
+ """源字节免传不复用上次任务的公共文件或产物标识。"""
+ client, _app = service
+ first = _create(client, [HTML])
+ client.put(first["files"][0]["upload"]["url"], content=HTML)
+ _wait_files(client, first, 1)
+ second = _create(client, [HTML])
+ assert second["files"][0]["file_id"] != first["files"][0]["file_id"]
+ assert "upload" not in second["files"][0]
+ completed = _wait_files(client, second, 1)
+ assert completed["files"][0]["result_url"].endswith(f"/{second['files'][0]['file_id']}/content")
+
+
+def test_openapi_separates_operation_schemas(service: tuple[TestClient, FastAPI]) -> None:
+ """OpenAPI 显式区分四类成功响应,查询的可选字段不再声明为必填。"""
+ client, _app = service
+ schema = client.get("/openapi.json").json()
+ for path, method, status, model in (
+ ("/v1/tasks", "post", "202", "CreateTaskResponse"),
+ ("/v1/tasks/{task_id}", "get", "200", "TaskDetailResponse"),
+ ("/v1/tasks/{task_id}/cancel", "post", "200", "CancelTaskResponse"),
+ ("/v1/tasks/{task_id}/uploads/{file_id}", "put", "200", "UploadFileResponse"),
+ ):
+ reference = schema["paths"][path][method]["responses"][status]["content"]["application/json"]["schema"]["$ref"]
+ assert reference.endswith("/" + model)
+ assert "delete" not in schema["paths"]["/v1/tasks/{task_id}"]
+ assert "delete" not in schema["paths"]["/v1/files/{file_id}"]
+ models = schema["components"]["schemas"]
+ assert "FileDeletionResponse" not in models
+ assert set(models["TaskFileDetail"]["required"]) == {"file_id", "file_name", "status"}
+ assert set(models["CreateTaskResponse"]["properties"]) == {"task_id", "status", "files"}
+ assert "upload" not in models["CanceledTaskFile"]["properties"]
+
+
+def test_reserved_output_ids_reject_collisions_and_late_publication(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """故意制造随机碰撞,验证取消、覆盖和已删除结果都不能重新占用旧 ID。"""
+ store = FileStore(tmp_path)
+ values = iter(["file-first", "file-first", "file-second"])
+
+ def next_id() -> str:
+ """把首次碰撞固定为可复现路径,第三个候选 ID 才可分配。"""
+ return next(values)
+
+ monkeypatch.setattr(store, "_new_file_id", next_id)
+ first, second = store.reserve_file_id(), store.reserve_file_id()
+ assert (first, second) == ("file-first", "file-second")
+ source = tmp_path / "output.zip"
+ source.write_bytes(b"complete output")
+ store.discard_file_id(first)
+ with pytest.raises(ValueError, match="not reserved"):
+ store.create_file_for_output_path("output.zip", source, job_id="job-one", file_id=first)
+ assert store.create_file_for_output_path("output.zip", source, job_id="job-two", file_id=second) == second
+ with pytest.raises(ValueError, match="already been published"):
+ store.create_file_for_output_path("other.zip", source, job_id="job-other", file_id=second)
+ store.delete_file(second)
+ with pytest.raises(ValueError, match="not reserved"):
+ store.create_file_for_output_path("output.zip", source, job_id="job-two", file_id=second)
+ store.finalize_outputs("job-two", int(time.time()))
+ assert not store._files and not store._pins and not store._reserved_output_ids
+ store.forget_file_id(first)
+ store.forget_file_id(second)
+ assert not store._allocated_file_ids and not store._task_file_ids
+
+
+def test_router_rejects_rebinding_and_deleted_result_resurrection() -> None:
+ """不同 worker 不能覆盖同一公共 ID,已删除映射不能被迟到完成响应复活。"""
+ registry = ResourceRegistry()
+ public_id = registry.reserve_file_id()
+ route = registry.register("file", owner_scope="owner", worker_id="a", upstream_id="file-worker-a", public_id=public_id)
+ with pytest.raises(ValueError, match="occupied"):
+ registry.register("file", owner_scope="owner", worker_id="b", upstream_id="file-worker-b", public_id=public_id)
+ assert registry.find("file", public_id) is route
+ registry.remove("file", public_id)
+ with pytest.raises(ValueError, match="consumed or discarded"):
+ registry.register("file", owner_scope="owner", worker_id="a", upstream_id="file-worker-a", public_id=public_id)
+ registry.forget_file_id(public_id)
+ assert not registry._allocated_file_ids and not registry._task_file_ids
+
+
[email protected]("service", ["router"], indirect=True)
[email protected]("changed_field", ["task_id", "file_id"])
+def test_router_rejects_mismatched_upload_receipt(
+ service: tuple[TestClient, FastAPI], monkeypatch: pytest.MonkeyPatch, changed_field: str
+) -> None:
+ """下游上传回执串到其他任务或文件时失败,迟到的真实产物也不能注册到公共 ID。"""
+ client, app = service
+ transport = app.state.test_transport
+ original = transport.handle_async_request
+
+ async def mismatched(request: httpx.Request) -> httpx.Response:
+ """保留真实 worker 上传和执行,只破坏回执中的身份字段。"""
+ response = await original(request)
+ if request.method == "PUT" and response.status_code == 200:
+ await response.aread()
+ payload = response.json()
+ payload[changed_field] = "another-resource"
+ return httpx.Response(200, json=payload)
+ return response
+
+ monkeypatch.setattr(transport, "handle_async_request", mismatched)
+ created = _create(client, [HTML])
+ file_id = created["files"][0]["file_id"]
+ assert client.put(created["files"][0]["upload"]["url"], content=HTML).status_code == 200
+ deadline = time.monotonic() + 10
+ while time.monotonic() < deadline:
+ detail = client.get(f"/v1/tasks/{created['task_id']}").json()
+ if detail["status"] == "failed":
+ break
+ time.sleep(0.01)
+ assert detail["status"] == "failed", detail
+ assert detail["files"][0]["error"]["code"] == "invalid_upstream_response"
+ assert "result_url" not in detail["files"][0]
+ assert client.get(f"/v1/files/{file_id}").status_code == 404
+
+
+def test_task_expiry_releases_only_its_file_id_reservations(service: tuple[TestClient, FastAPI]) -> None:
+ """取消任务回收后释放 ID 索引,其他仍等待上传的任务继续持有自己的预留。"""
+ client, app = service
+ created, other = _create(client, [HTML]), _create(client, [SECOND])
+ file_id, other_id = created["files"][0]["file_id"], other["files"][0]["file_id"]
+ assert client.post(f"/v1/tasks/{created['task_id']}" + "/cancel").status_code == 200
+
+ async def expire() -> None:
+ """在服务所属循环等待取消清理,再模拟保留期结束。"""
+ store = app.state.task_store
+ record = store._records[created["task_id"]]
+ await record.operation
+ record.retention_epoch = time.time() - 2
+ store.retention_seconds = 1
+ store.collect_expired()
+
+ client.portal.call(expire)
+ allocator = app.state.file_store if hasattr(app.state, "file_store") else app.state.registry
+ assert file_id not in allocator._allocated_file_ids and file_id not in allocator._task_file_ids
+ assert other_id in allocator._allocated_file_ids and other_id in allocator._task_file_ids
diff --git a/tests/unittest/test_tasks_sdk.py b/tests/unittest/test_tasks_sdk.py
index 25726793..580944b0 100644
--- a/tests/unittest/test_tasks_sdk.py
+++ b/tests/unittest/test_tasks_sdk.py
@@ -42,7 +42,9 @@ def zip_output() -> bytes:
return stream.getvalue()
-def task_snapshot(status: str = "completed", *, upload: bool = False) -> dict[str, Any]:
+def task_snapshot(
+ status: str = "completed", *, upload: bool = False, file_name: str = "file.pdf", size: int = 3
+) -> dict[str, Any]:
"""提供逐文件内嵌上传描述,不伪造已移除的查询链接或顶层档位。"""
return {
"task_id": "task-one",
@@ -50,9 +52,9 @@ def task_snapshot(status: str = "completed", *, upload: bool = False) -> dict[st
"output_formats": ["default"],
"files": [
{
- "client_file_id": "file",
- "file_name": "file.pdf",
- "bytes": 3,
+ "file_id": "file-one",
+ "file_name": file_name,
+ "bytes": size,
"status": status,
"upload": {
"url": "https://storage.test/input",
@@ -116,15 +118,33 @@ def test_task_query_uses_configured_prefix_without_status_url(
@pytest.mark.parametrize("asynchronous", [False, True])
-def test_tasks_sdk_rejects_missing_nested_upload(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, asynchronous: bool) -> None:
- """缺少新 upload 字段的旧响应不能被当作缓存命中或触发旧字段回退。"""
+def test_tasks_sdk_accepts_missing_upload_and_polls(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, asynchronous: bool
+) -> None:
+ """创建回执省略上传动作时只轮询,成功后用详情下载,不触发重复提交或上传。"""
source = tmp_path / "file.pdf"
source.write_bytes(b"pdf")
- snapshot = task_snapshot("waiting-file", upload=True)
- del snapshot["files"][0]["upload"]
- bind_transport(monkeypatch, lambda _: httpx.Response(202, json=snapshot))
- with pytest.raises(api_client._V1APIError, match="upload descriptor"):
- parse(MinerUApiParser(api_url="https://api.test"), source, asynchronous)
+ methods: list[str] = []
+
+ def handle(request: httpx.Request) -> httpx.Response:
+ """分别提供精简创建回执、查询详情和真实 ZIP 字节。"""
+ methods.append(request.method)
+ if request.method == "POST":
+ return httpx.Response(
+ 202,
+ json={
+ "task_id": "task-one",
+ "status": "waiting-file",
+ "files": [{"file_id": "file-one", "file_name": "file.pdf", "status": "waiting-file"}],
+ },
+ )
+ if request.url.host == "api.test":
+ return httpx.Response(200, json=task_snapshot())
+ return httpx.Response(200, content=zip_output())
+
+ bind_transport(monkeypatch, handle)
+ assert len(parse(MinerUApiParser(api_url="https://api.test"), source, asynchronous).pages) == 1
+ assert methods == ["POST", "GET", "GET"]
@pytest.mark.parametrize("asynchronous", [False, True])
@@ -137,7 +157,9 @@ def test_tasks_sdk_upload_cache_and_lost_response(
source = tmp_path / "report.pdf"
source.write_bytes(b"%PDF-example")
calls: list[httpx.Request] = []
- state = task_snapshot("completed" if cached else "waiting-file", upload=not cached)
+ state = task_snapshot(
+ "completed" if cached else "waiting-file", upload=not cached, file_name=source.name, size=source.stat().st_size
+ )
def handle(request: httpx.Request) -> httpx.Response:
"""记录线上协议,不接受任何独立上传或 Jobs 路由。"""
@@ -154,7 +176,7 @@ def test_tasks_sdk_upload_cache_and_lost_response(
assert request.headers["content-length"] == str(source.stat().st_size)
assert "transfer-encoding" not in request.headers
assert "authorization" not in request.headers
- state.update(task_snapshot())
+ state.update(task_snapshot(file_name=source.name, size=source.stat().st_size))
if lost_upload_response:
raise httpx.ReadError("response lost")
return httpx.Response(200, json=state)
@@ -245,6 +267,9 @@ def test_tasks_sdk_transport_recovery(
("task_id", "other"),
("task_id", ".."),
("output_formats", ["html"]),
+ ("file_id", "file-another"),
+ ("file_name", "another.pdf"),
+ ("bytes", 4),
],
)
def test_tasks_sdk_rejects_changed_identity(
@@ -256,7 +281,12 @@ def test_tasks_sdk_rejects_changed_identity(
def handle(request: httpx.Request) -> httpx.Response:
"""提交合法,后续查询注入字段变化。"""
- response = task_snapshot("pending") if request.method == "POST" else {**task_snapshot(), field: value}
+ response = task_snapshot("pending") if request.method == "POST" else task_snapshot()
+ if request.method != "POST":
+ if field in {"file_id", "file_name", "bytes"}:
+ response["files"][0][field] = value
+ else:
+ response[field] = value
return httpx.Response(200, json=response)
bind_transport(monkeypatch, handle)
@@ -396,14 +426,14 @@ def test_tasks_sdk_retries_transient_poll_responses(
"""首次创建成功,按预算注入轮询故障,之后返回可读取的完整结果。"""
if request.method == "POST":
counts["post"] += 1
- return httpx.Response(202, json=task_snapshot("pending"))
+ return httpx.Response(202, json=task_snapshot("pending", file_name=source.name))
if request.url.host == "api.test":
counts["query"] += 1
if counts["query"] <= failures:
return httpx.Response(
status, headers={"Retry-After": "2"}, json={"error": {"code": "temporary", "message": "retry later"}}
)
- return httpx.Response(200, json=task_snapshot())
+ return httpx.Response(200, json=task_snapshot(file_name=source.name))
return httpx.Response(200, content=zip_output())
async def sleep(delay: float) -> None: