# Join / Merge

> 将多个执行分支汇合回单一路径。

Source: https://docs.sommatic.ai/zh/nodes/flow.join/

- 标识: `flow.join`
- 类别: 流程控制
- 版本: 1.0.0
- 状态: 可用
- 执行方式: sync

将多个执行分支汇合回单一路径。

该算子实现“扇入”（Fan-In）同步模式。当并发拆分（扇出，Fan-Out）的结果需要重新汇总以便聚合处理时，它必不可少。它会按所配置的模式等待上游信号，然后再继续执行。

**模式：**
- **Wait All：** 阻塞直到所有入站分支全部完成。适用于需要全部结果的并行处理。
- **Wait Any：** 只要第一个分支完成就继续执行。适用于竞争条件或冗余校验。

**输出：**
结果是一个数组，包含所有已汇合分支的载荷：`[result1, result2, ...]`。

## 配置

- `mode` (string, 可选): 同步策略。 默认值: `wait_all`. 可选值: `wait_all`, `wait_any`.
- `timeout_ms` (integer, 可选): 最长等待时间。0 表示无限等待。 默认值: `0`.

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

## 输出端口

- `out` (默认): 满足汇合条件时激活。
- `timeout`: 等待时间超过超时设置时激活。
- `error`: 发生内部故障时激活

## 输入契约

- `payload` (object, 可选)

## 输出契约

- `payload` (array<object>, 可选)

## 在表达式中

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

- `$("Join / Merge").item.json.payload` (array) **worker 不返回：读取结果为 undefined.**
- `$("Join / Merge").item.json.merged` (array) = `[…] (2)` (编辑器不提示)
- `$("Join / Merge").item.json.count` (number) = `2` (编辑器不提示)
- `$("Join / Merge").item.json.mode` (string) = `"wait_all"` (编辑器不提示)


## 工作原理

收集 `flow.split` 展开的各元素结果，在 split 的 `done` 信号和所有元素都到达后，作为一个数组输出。

1. 引擎会缓存每次到达 join 节点的数据，而不是立即执行。经 `done` 端口到达时标记闸门就绪，并将期望数量设为 `total_items`；其他到达则把其 payload 加入列表。
2. 当 `done` 已到达且列表数量不少于期望值时，引擎以该列表作为 `inputs` 执行一次 worker，并清空闸门。
3. worker 通过 `out` 返回 `{ merged, count, mode }`；`merged` 保持到达顺序。
4. 使用“Execute step”（没有引擎输入）时，`merged` 由运行图中已执行节点的输出构成；若没有则为 `[payload]`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-collect-orders",
  "label": "Collect orders",
  "operator_slug": "flow.join",
  "operator_version": "1.0.0",
  "config": {
    "mode": "wait_all",
    "timeout_ms": 0
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "merged": [
      {
        "order_id": "ord_1",
        "status": "synced"
      },
      {
        "order_id": "ord_2",
        "status": "synced"
      }
    ],
    "count": 2,
    "mode": "wait_all"
  },
  "port": "out"
}
```

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

### `out`

split 的 `done` 信号之后所有元素均已到达。

```json
{
  "merged": [
    {
      "order_id": "ord_1",
      "status": "synced"
    },
    {
      "order_id": "ord_2",
      "status": "synced"
    }
  ],
  "count": 2,
  "mode": "wait_all"
}
```

### `timeout`

从不触发：`timeout_ms` 会被忽略。

### `error`

worker 从不输出此端口。

## 代码中的行为

- `mode`: 仅在输出中回显：`wait_any` 的行为与 `wait_all` 相同。
- `timeout_ms`: 被忽略：join 永不超时。

## 说明与限制

- 若没有从 `flow.split` 的 `done` 端口连到 join 的连线，join 永远不会执行：普通并行分支的到达会被一直缓存，join 之后的节点都不会执行，而运行仍会完成。
- 若某个元素分支在别处结束（`error` 端口、没有连线的 `false` 端口），或 split 使用 `batch_size` > 1，则永远达不到期望数量，join 不会执行。
- split 收到空数组时只发送 `done`；此时 join 以 `merged: []`、`count: 0` 执行。
- join 闸门仅在当前运行的内存中存在。


## 契约（JSON Schema）

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

```json
{
  "slug": "flow.join",
  "name": "Join / Merge",
  "category": "flow",
  "version": "1.0.0",
  "description": "Consolidates multiple execution branches back into a single path.\n\n  This operator implements the 'Fan-In' synchronization pattern. It is essential when a concurrent split (Fan-Out) needs to be gathered back for aggregated processing. It waits for upstream signals based on the configured mode before proceeding.\n\n  **Modes:**\n  - **Wait All:** Blocks until ALL incoming branches have completed. Ideal for parallel processing where all results are needed.\n  - **Wait Any:** Proceeds as soon as the FIRST branch completes. ideal for race conditions or redundancy checks.\n\n  **Output:**\n  The result is an array containing the payloads from all joined branches: `[result1, result2, ...]`.",
  "capabilities": [
    "fan-in",
    "aggregation",
    "sync"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "mode": {
        "type": "string",
        "enum": [
          "wait_all",
          "wait_any"
        ],
        "default": "wait_all",
        "title": "Join Mode",
        "description": "Strategy for synchronization."
      },
      "timeout_ms": {
        "type": "integer",
        "title": "Timeout (ms)",
        "description": "Maximum time to wait. 0 means infinite wait.",
        "default": 0
      },
      "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",
    "description": "Receives multiple upstream payloads (handled by engine).",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "description": "Array of results from the joined branches.",
    "properties": {
      "payload": {
        "type": "array",
        "items": {
          "type": "object"
        }
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Merged",
      "is_default": true,
      "description": "Active when join condition is met."
    },
    {
      "port_id": "timeout",
      "label": "Timeout",
      "description": "Active if the join waits longer than the timeout."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Active on internal failure"
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "merge",
    "aggregate",
    "synchronize",
    "fan-in"
  ],
  "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": {
    "mode": {
      "type": "string",
      "enum": [
        "wait_all",
        "wait_any"
      ],
      "default": "wait_all",
      "title": "Join Mode",
      "description": "Strategy for synchronization."
    },
    "timeout_ms": {
      "type": "integer",
      "title": "Timeout (ms)",
      "description": "Maximum time to wait. 0 means infinite wait.",
      "default": 0
    },
    "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",
  "description": "Receives multiple upstream payloads (handled by engine).",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "Array of results from the joined branches.",
  "properties": {
    "payload": {
      "type": "array",
      "items": {
        "type": "object"
      }
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Merged",
    "is_default": true,
    "description": "Active when join condition is met."
  },
  {
    "port_id": "timeout",
    "label": "Timeout",
    "description": "Active if the join waits longer than the timeout."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Active on internal failure"
  }
]
```
