# Read State

> 从工作流状态存储中读取一个持久化值。

Source: https://docs.sommatic.ai/zh/nodes/ops.state.read/

- 标识: `ops.state.read`
- 类别: 运维
- 版本: 1.0.0
- 状态: 部分可用. `instance` 范围始终返回 `miss`。工作流范围的状态仅在草稿测试运行中可用，已发布版本的运行中不可用。
- 执行方式: sync

从工作流状态存储中读取一个持久化值。

该算子用于访问之前步骤保存的数据，甚至是其他工作流保存的数据（使用 Global/Case 作用域）。它为长时间运行或分布式执行提供了跨步骤保持上下文的方式。

**行为：**
- 在指定作用域中查找该键。
- 找到时返回其值。
- 未找到时触发“miss”端口，以便执行回退逻辑。

**适用场景：**
- 读取缓存的用户档案。
- 通过状态标志确认之前的步骤是否已完成。

## 配置

- `scope` (string, 必填): 读取的可见范围（Instance、Case 或系统级 Global）。 默认值: `instance`. 可选值: `instance`, `case`, `global`.

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

## 输出端口

- `success` (默认): 成功读取值。
- `miss`: 键不存在或已过期。
- `error`: 存储连接错误。

## 输入契约

- `key` (string, 必填): 状态变量的唯一键。

## 输出契约

- `value` (any, 可选): 存储的数据。

## 在表达式中

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

- `$("Read State").item.json.value` (any) = `"2026-11-25T23:00:00.000Z"`: 存储的数据。


## 工作原理

按 `key` 读取值。`global` 和 `case` 作用域读取工作流键值状态（`kv_state`）；在当前运行时中，`instance` 作用域始终返回 `miss`。

1. 将输入项与解析后的配置合并（配置优先）。
2. 使用 `scope`（默认 `instance`）；`key` 为空时以 `Missing 'key'` 从 `error` 输出。
3. `global`：在 `$input.$kv_state` 中查找 `<key>`。`case`：在同一存储中查找 `case:<key>`。
4. `instance`：读取 worker 上下文中的 `state`，而运行时不提供它，因此值始终为 undefined。
5. 值为 undefined 时以 `{ key }` 从 `miss` 输出；否则以 `{ value }` 从 `success` 输出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-read-last-sync",
  "label": "Read last sync time",
  "operator_slug": "ops.state.read",
  "operator_version": "1.0.0",
  "config": {
    "scope": "global",
    "key": "last_sync_at"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "success",
  "data": {
    "value": "2026-11-25T23:00:00.000Z"
  }
}
```

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

### `success`

该键存在于 `kv_state` 中（`global` 或 `case` 作用域）。

```json
{
  "value": "2026-11-25T23:00:00.000Z"
}
```

### `miss`

该键不在 `kv_state` 中、运行未收到 `kv_state`，或作用域为 `instance`。

```json
{
  "key": "last_sync_at"
}
```

### `error`

`key` 为空。输出为整个返回对象 `{ port, error }`。

```json
{
  "port": "error",
  "error": "Missing 'key'"
}
```

## 代码中的行为

- `key`: 不在配置 schema 中（仅出现在输入契约中），但会从节点配置读取；节点上未设置时从输入项读取：`key`。
- `scope`: `case` 并不按案例隔离：它只是在与 `global` 相同的按工作流存储中给键加上 `case:` 前缀。`global` 的范围是单个工作流，而不是整个系统。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing 'key'` | `error` | 节点和输入项中都没有设置 `key`。 |

## 说明与限制

- 键值状态保存在工作流定义的元数据（`kv_state`）中，由该工作流的所有运行共享。只有当运行使用草稿图时，后端才会在启动时把它注入为 `$input.$kv_state`；已发布版本的运行不会收到。写入（每个步骤的 `meta.kv_state`）在运行结束后才合并进元数据，因此同一次运行中的后续节点看不到。没有过期机制。
- 只有 `ops.dedupe`、`ops.checkpoint` 和 `ops.state.write` 会写入值，而它们在当前运行时中都会失败，因此 `kv_state` 只包含之前已保存的内容。
- 从 `error` 端口输出不会使运行失败：引擎沿 `error` 上的连线继续；若没有连线，该分支直接结束。
- `execution` 设置（`retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail`、`timeout_ms`）可以填写，但本 worker 和引擎都不会应用。


## 契约（JSON Schema）

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

```json
{
  "slug": "ops.state.read",
  "name": "Read State",
  "category": "ops",
  "version": "1.0.0",
  "description": "Retrieves a persistent value from the workflow state store.\n\n  This operator is used to access data saved in previous steps or even from other workflows (using Global/Case scope). It provides a way to maintain context across long-running or distributed executions.\n\n  **Behavior:**\n  - Attempts to find the key in the specified scope.\n  - If found, returns the value.\n  - If not found, triggers the 'miss' port to allow for fallback logic.\n\n  **Use Cases:**\n  - Retrieving a cached user profile.\n  - Validating if a previous step completed via a state flag.",
  "capabilities": [
    "state",
    "persistence",
    "read",
    "store"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "scope"
    ],
    "properties": {
      "scope": {
        "type": "string",
        "enum": [
          "instance",
          "case",
          "global"
        ],
        "default": "instance",
        "title": "State Scope",
        "description": "Visibility level to read from (Instance, Case, or Global system-wide)."
      },
      "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": {
      "key": {
        "type": "string",
        "description": "The unique key of the state variable."
      }
    },
    "required": [
      "key"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "description": "The retrieved value.",
    "properties": {
      "value": {
        "type": "any",
        "description": "The stored data."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Found",
      "is_default": true,
      "description": "Value retrieved successfully."
    },
    {
      "port_id": "miss",
      "label": "Not Found",
      "description": "Keys does not exist or has expired."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Storage connectivity error."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "state",
    "database",
    "persistence",
    "read"
  ],
  "is_stateful": true,
  "publisher": {
    "identity": "org_link_loom",
    "profile": {
      "name": "Link Loom",
      "verified": true,
      "url": "https://me.veripass.com/link-loom",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "required": [
    "scope"
  ],
  "properties": {
    "scope": {
      "type": "string",
      "enum": [
        "instance",
        "case",
        "global"
      ],
      "default": "instance",
      "title": "State Scope",
      "description": "Visibility level to read from (Instance, Case, or Global system-wide)."
    },
    "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": {
    "key": {
      "type": "string",
      "description": "The unique key of the state variable."
    }
  },
  "required": [
    "key"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "The retrieved value.",
  "properties": {
    "value": {
      "type": "any",
      "description": "The stored data."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Found",
    "is_default": true,
    "description": "Value retrieved successfully."
  },
  {
    "port_id": "miss",
    "label": "Not Found",
    "description": "Keys does not exist or has expired."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Storage connectivity error."
  }
]
```
