> ## Documentation Index
> Fetch the complete documentation index at: https://docs.qoder.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 取消 Batch

> 取消正在执行或等待中的 Batch。

`POST /api/v1/forward/batches/{batch_id}/cancel`

发起取消后，Forward 会清空队列、取消 pending 任务，并对 running task 调用 CancelSession。

## 请求头

| Header          | 是否必填 | 说明             |
| --------------- | ---- | -------------- |
| Authorization   | 是    | `Bearer <PAT>` |
| Idempotency-Key | 否    | 有副作用请求可选的幂等键。  |

## 路径参数

| 参数        | 类型     | 是否必填 | 说明        |
| --------- | ------ | ---- | --------- |
| batch\_id | string | 是    | Batch ID。 |

## 示例请求

```bash theme={null}
curl -s -X POST 'https://api.qoder.com/api/v1/forward/batches/batch_processing001/cancel' \
  -H "Authorization: Bearer $QODER_PAT"
```

## 示例响应

**HTTP 200 OK**

```json theme={null}
{
  "id": "batch_processing001",
  "object": "batch",
  "status": "cancelling",
  "input_file_id": "file_input002",
  "completion_window": "24h",
  "created_at": "2026-07-06T11:59:02Z",
  "expires_at": "2026-07-07T11:59:02Z",
  "request_counts": {
    "total": 10,
    "pending": 0,
    "running": 3,
    "completed": 7,
    "failed": 0,
    "cancelled": 0,
    "expired": 0
  },
  "usage": null
}
```

响应为发起取消时的状态快照：若仍有 running task，`status` 为中间态 `cancelling`；若无 running task 则直接返回 `cancelled`。已处终态的 Batch 幂等返回当前对象。

## 响应字段

| 字段  | 类型     | 说明        |
| --- | ------ | --------- |
| 返回值 | object | Batch 对象。 |

## 取消流程

1. 已处于终态的 Batch：幂等返回 `200`，不做任何操作。
2. CAS 状态转换 `validating|queued|processing → cancelling`。
3. 清空 Redis 队列，批量标记 pending 任务为 `cancelled`。
4. 对每个 running task 调用 `CancelSession`。
5. 若无 running task，立即触发 finalize；否则等待最后一个 `CompleteTask` 驱动 finalize。

## 错误码

| HTTP | Type                   | Code                      | 触发条件             |
| ---- | ---------------------- | ------------------------- | ---------------- |
| 404  | `not_found_error`      | `batch_not_found`         | Batch 不存在或跨用户访问。 |
| 401  | `authentication_error` | `authentication_required` | PAT 无效或已过期。      |

## 注意事项

* 取消是异步操作，响应 `cancelling` 表示已发起取消，需轮询详情确认终态。
* 终态 Batch 取消为幂等操作，返回 `200`。

## 相关

<CardGroup cols={2}>
  <Card title="查询 Batch 详情" icon="file-text" href="/zh/cloud-agents/api/forward/batches/get" />

  <Card title="获取输出文件" icon="download" href="/zh/cloud-agents/api/forward/batches/get-output" />
</CardGroup>
