# Checkpoint

> 在工作流执行中标记一个有保证的持久化点。

Source: https://docs.sommatic.ai/zh/nodes/ops.checkpoint/

- 标识: `ops.checkpoint`
- 类别: 运维
- 版本: 1.0.0
- 状态: 实验性. 目前始终失败：worker 调用了运行时日志器不提供的 `logger.debug`，因此每次运行都会以 "logger.debug is not a function" 从 `error` 端口输出。修复前请勿使用。
- 执行方式: sync

在工作流执行中标记一个有保证的持久化点。

检查点相当于“存档点”。工作流崩溃或重启后，可以从最近一个成功的检查点恢复，而不必从头开始。它还支持幂等性，可识别重复请求以防止重复处理。

**行为：**
- **首次运行：** 持久化检查点并触发“success”。
- **重放：** 检测到检查点已存在，触发“skip”（或返回之前的输出）。
- **哈希：** 可选地对输入载荷做哈希，确保是*完全相同*的请求。

**适用场景：**
- 在信用卡扣款与商品发货之间。
- 确保邮件恰好发送一次。

## 配置

- `payload_hash_mode` (boolean, 可选): 为 true 时，输入载荷必须完全一致才会被视为重复重放。 默认值: `false`.

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `success` (默认): 检查点已创建，继续执行。
- `skip`: 检查点已存在，跳过下游逻辑。
- `error`: 持久化失败。

## 输入契约

- `idempotency_key` (string, 必填): 本次具体操作执行的唯一标识符。

## 在表达式中

后续节点可通过 `$("Checkpoint").item.json.<路径>` 读取此节点输出中的内容（请把 `Checkpoint` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `success` 返回的路径，依据“端口”一节所示的输出。

此节点未声明输出字段。


## 工作原理

设计用途是在工作流键值状态中记住幂等键，从而跳过重复执行。在当前运行时中，它总是在读写任何状态之前以 `logger.debug is not a function` 从 `error` 输出。

1. 将输入项与解析后的配置合并（配置优先）。
2. 幂等键为空时，以 `Missing 'idempotency_key'` 从 `error` 输出。
3. 构建状态键 `chk:<idempotency_key>`；启用 `payload_hash_mode` 时追加 `:<md5>`。
4. 调用 `logger.debug()` 时抛错；worker 捕获后从 `error` 输出。下面的步骤目前不会执行。
5. 在 `$input.$kv_state` 中查找该键。找到时：携带已保存的 payload 从 `skip` 输出。
6. 未找到时：以 `{}` 从 `success` 输出，并通过 `meta.kv_state` 请求后端在该键下保存 `{ timestamp, payload }`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-checkpoint-order",
  "label": "Checkpoint order",
  "operator_slug": "ops.checkpoint",
  "operator_version": "1.0.0",
  "config": {
    "idempotency_key": "{{ $json.order_id }}",
    "payload_hash_mode": false
  }
}
```

### Envelope

```json
{
  "ok": false,
  "port": "error",
  "data": {
    "port": "error",
    "error": "logger.debug is not a function"
  }
}
```

## 输出端口 (代码中的行为)

### `success`

在当前运行时中不会到达：`logger.debug()` 调用会先失败。此处展示代码构建的数据结构。

```json
{}
```

### `skip`

在当前运行时中不会到达：`logger.debug()` 调用会先失败。此处展示代码构建的数据结构。

```json
{
  "order_id": "ord_123",
  "total": 129.9
}
```

### `error`

目前每次运行都会如此。由于 worker 未设置 `data`，输出为整个返回对象 `{ port, error }`。

```json
{
  "port": "error",
  "error": "logger.debug is not a function"
}
```

## 代码中的行为

- `idempotency_key`: 不在配置 schema 中（仅出现在输入契约中），但会从节点配置读取；节点上未设置时从输入项读取：`idempotency_key`。
- `payload_hash_mode`: 哈希基于 worker 上下文中的 `payload` 计算，而运行时不会设置它，因此始终是 `{}` 的 MD5：该后缀无法区分不同的 payload。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `logger.debug is not a function` | `error` | Worker 调用了运行时 logger 不提供的 `logger.debug()`。每次运行都会发生，任何配置都无法避免。 |
| `Missing 'idempotency_key'` | `error` | 节点和输入项中都没有设置 `idempotency_key`。 |

## 说明与限制

- Worker 调用了 `logger.debug()`，而运行时 logger 没有该方法（只提供 `info`、`warning`、`error`、`log` 和 `success`）。每次运行该调用都会抛错。
- 键值状态保存在工作流定义的元数据（`kv_state`）中，由该工作流的所有运行共享。只有当运行使用草稿图时，后端才会在启动时把它注入为 `$input.$kv_state`；已发布版本的运行不会收到。写入（每个步骤的 `meta.kv_state`）在运行结束后才合并进元数据，因此同一次运行中的后续节点看不到。没有过期机制。
- Worker 把字段直接放在顶层而不是 `data` 中，因此引擎把整个返回对象（包括 `port`）作为节点输出。
- 从 `error` 端口输出不会使运行失败：引擎沿 `error` 上的连线继续；若没有连线，该分支直接结束。
- `execution` 设置（`retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail`、`timeout_ms`）可以填写，但本 worker 和引擎都不会应用。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "ops.checkpoint",
  "name": "Checkpoint",
  "category": "ops",
  "version": "1.0.0",
  "description": "Marks a guaranteed durability point in the workflow execution.\n\n  A Checkpoint acts as a \"Save Game\" spot. If the workflow crashes or is restarted, it can resume from the last successful checkpoint rather than restarting from the beginning. It also supports Idempotency, identifying duplicate requests to prevent double-processing.\n\n  **Behavior:**\n  - **First Run:** Persists the checkpoint and triggers 'success'.\n  - **Replay:** Detects the checkpoint exists and triggers 'skip' (or returns the previous output).\n  - **Hashing:** Can optionally hash the input payload to ensure it's the *exact same* request.\n\n  **Use Cases:**\n  - Between charging a credit card and shipping a product.\n  - Ensuring an email is sent exactly once.",
  "capabilities": [
    "reliability",
    "recovery",
    "idempotency",
    "checkpoint"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "payload_hash_mode": {
        "type": "boolean",
        "default": false,
        "title": "Strict Payload Hashing",
        "description": "If true, the input payload must match exactly to be considered a duplicate replay."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "idempotency_key": {
        "type": "string",
        "description": "Unique identifier for this specific operation execution."
      }
    },
    "required": [
      "idempotency_key"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "description": "Empty on success, or previous result on skip.",
    "properties": {}
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Success",
      "is_default": true,
      "description": "Checkpoint created. Continue execution."
    },
    {
      "port_id": "skip",
      "label": "Skip (Duplicate)",
      "description": "Checkpoint already exists. Skipping downstream logic."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Failed to persist."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "reliability",
    "recovery",
    "idempotency"
  ],
  "is_stateful": true,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "payload_hash_mode": {
      "type": "boolean",
      "default": false,
      "title": "Strict Payload Hashing",
      "description": "If true, the input payload must match exactly to be considered a duplicate replay."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "idempotency_key": {
      "type": "string",
      "description": "Unique identifier for this specific operation execution."
    }
  },
  "required": [
    "idempotency_key"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "Empty on success, or previous result on skip.",
  "properties": {}
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Success",
    "is_default": true,
    "description": "Checkpoint created. Continue execution."
  },
  {
    "port_id": "skip",
    "label": "Skip (Duplicate)",
    "description": "Checkpoint already exists. Skipping downstream logic."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Failed to persist."
  }
]
```
