# Workflow Chain

> Invokes another workflow and optionally waits for its result.

Source: https://docs.sommatic.ai/en/nodes/workflow.chain/

- Slug: `workflow.chain`
- Family: Composition
- Version: 1.0.0
- Status: Available
- Execution: async

Invokes another workflow and optionally waits for its result.

This operator enables peer-to-peer workflow chaining. It triggers a target workflow and can operate in synchronous (wait for result) or asynchronous (fire-and-forget) mode.

**Features:**
- **Sync Mode:** Waits for the target workflow to complete and returns its result.
- **Async Mode:** Fires the target workflow and continues immediately with the instance ID.
- **Traceability:** Correlation ID links both workflow instances for audit and debugging.
- **Payload Forwarding:** Define exactly what data to pass to the target workflow.

**Use Cases:**
- Composing complex processes from reusable workflow modules.
- Delegating specialized processing (e.g., validation, enrichment) to dedicated workflows.
- Fan-out patterns where one workflow triggers multiple independent workflows.

## Configuration

- `target_flow_definition_id` (string, required): The workflow to invoke when this node executes.
- `payload` (object, optional): Data to send to the target workflow. Use {{expressions}} to reference upstream node outputs. If empty, the current node input ($json) is forwarded.

Its configuration shows the shared execution settings, but this node does not apply retries (`retryOnFail`, `maxTries`) yet. `continueOnFail` is not applied by any node.

## Output ports

- `out` (default): Target workflow completed successfully (sync) or dispatched (async).
- `error`: Target workflow failed, timed out, or could not be found.

## Input contract

- `target_flow_definition_id` (string, required)
- `payload` (object, optional)

## Output contract

- `instance_id` (string, optional): The ID of the created workflow instance.
- `status` (string, optional): Final status of the target workflow (sync) or "running" (async).
- `result` (object, optional): The target workflow result (sync mode only).

## In expressions

What a later node can read from this node's output with `$("Workflow Chain").item.json.<path>` (write your node's label instead of `Workflow Chain`). **Editor** marks the paths the workflow editor suggests under Previous Nodes (the output contract); **Worker** marks the paths the worker really returns through `out`, from the output shown in Ports.

- `$("Workflow Chain").item.json.instance_id` (string) = `"<flow_instance_id>"`: The ID of the created workflow instance.
- `$("Workflow Chain").item.json.status` (string) = `"completed"`: Final status of the target workflow (sync) or "running" (async).
- `$("Workflow Chain").item.json.result` (object) = `{…}`: The target workflow result (sync mode only).
- `$("Workflow Chain").item.json.result.id` (string) = `"<flow_instance_result_id>"` (Not suggested by the editor)
- `$("Workflow Chain").item.json.result.flow_instance_id` (string) = `"<flow_instance_id>"` (Not suggested by the editor)
- `$("Workflow Chain").item.json.result.correlation_id` (string) = `"<correlation_id>"` (Not suggested by the editor)
- `$("Workflow Chain").item.json.result.status` (object) = `{…}` (Not suggested by the editor)
- `$("Workflow Chain").item.json.result.outcome_category` (string) = `"success"` (Not suggested by the editor)
- `$("Workflow Chain").item.json.result.duration_ms` (number) = `1840` (Not suggested by the editor)
- `$("Workflow Chain").item.json.result.error_summary` (null) = `null` (Not suggested by the editor)
- `$("Workflow Chain").item.json.result.final_output_envelope` (object) = `{…}` (Not suggested by the editor)
- `$("Workflow Chain").item.json.result.metrics` (object) = `{…}` (Not suggested by the editor)
- `$("Workflow Chain").item.json.steps` (null) = `null` (Not suggested by the editor)
- `$("Workflow Chain").item.json.correlation_id` (string) = `"chain-8f3k2m9q1x7v4b6n0z5c"` (Not suggested by the editor)


## How it works

Starts another workflow of the same organization by its definition id, passing a payload and a chain context, and either waits for its terminal result (`sync`) or continues once it is dispatched (`async`).

1. Resolves the config. Fails through `error` when `target_flow_definition_id` is empty. The payload sent is the configured `payload` or, when it is not set, the node input (`$json`).
2. Resolves the organization from the run (`$organization_id`, else `organization_id` in the run input or the node input) and the environment of the child: `prod` when the parent runs a published version, `test` otherwise.
3. Builds the chain context: caller definition id, instance id, slug and node id, a new `correlation_id` (`chain-…`) and the `root_flow_instance_result_id` of the whole chain, inherited unchanged from the parent when the parent was itself chained.
4. Asks the backend to run the target. In `prod` the backend uses the target's default published version (or its latest one); the child receives `$input` = `{ data: <payload>, chain_context }`.
5. `sync`: consumes a streaming response that relays the child's per-node progress to the parent's timeline and ends with the terminal result. `async`: returns once the child is dispatched.
6. A 2xx answer leaves through `out` with `{ instance_id, status, result, steps: null, correlation_id }`; anything else through `error`.

## In a workflow

### Node

```json
{
  "node_id": "node-score-applicant",
  "label": "Score applicant",
  "operator_slug": "workflow.chain",
  "operator_version": "1.0.0",
  "config": {
    "target_flow_definition_id": "<flow_definition_id>",
    "payload": {
      "applicant_id": "{{ $json.applicant_id }}",
      "amount": "{{ $json.amount }}"
    },
    "execution": {
      "mode": "sync",
      "timeout_ms": 30000
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "instance_id": "<flow_instance_id>",
    "status": "completed",
    "result": {
      "id": "<flow_instance_result_id>",
      "flow_instance_id": "<flow_instance_id>",
      "correlation_id": "<correlation_id>",
      "status": {
        "id": 5,
        "name": "completed",
        "title": "Completed",
        "color": "#2e7d32"
      },
      "outcome_category": "success",
      "duration_ms": 1840,
      "error_summary": null,
      "final_output_envelope": {
        "node_id": "node-score",
        "port": "out",
        "payload": {
          "score": 0.92,
          "approved": true
        }
      },
      "metrics": {}
    },
    "steps": null,
    "correlation_id": "chain-8f3k2m9q1x7v4b6n0z5c"
  },
  "meta": {
    "target_flow_definition_id": "<flow_definition_id>",
    "mode": "sync",
    "correlation_id": "chain-8f3k2m9q1x7v4b6n0z5c"
  },
  "port": "out"
}
```

## Output ports (behaviour in the code)

### `out`

The backend accepted the chain. In `sync`, `status` is the child's final status name and `result` a trimmed run result (its own `status` is a status object) whose `final_output_envelope.payload` holds the child's last output; this port also fires when the child ended `failed`, so check `status`. In `async`, `status` is `running` and `result` is `null`. `steps` is always `null`; `meta` carries `target_flow_definition_id`, `mode` and `correlation_id`.

```json
{
  "instance_id": "<flow_instance_id>",
  "status": "completed",
  "result": {
    "id": "<flow_instance_result_id>",
    "flow_instance_id": "<flow_instance_id>",
    "correlation_id": "<correlation_id>",
    "status": {
      "id": 5,
      "name": "completed",
      "title": "Completed",
      "color": "#2e7d32"
    },
    "outcome_category": "success",
    "duration_ms": 1840,
    "error_summary": null,
    "final_output_envelope": {
      "node_id": "node-score",
      "port": "out",
      "payload": {
        "score": 0.92,
        "approved": true
      }
    },
    "metrics": {}
  },
  "steps": null,
  "correlation_id": "chain-8f3k2m9q1x7v4b6n0z5c"
}
```

### `error`

The backend rejected the chain (data is `{ status, message, correlation_id }`), the call failed (`{ error, response }`), or it timed out (`{ error: "TIMEOUT", message }`). For a missing target, backend URL or organization the envelope has no `data`, so the next node receives `{ ok: false, errors: [...], port: "error" }`.

```json
{
  "status": 500,
  "message": "No published version found for the target workflow",
  "correlation_id": "chain-8f3k2m9q1x7v4b6n0z5c"
}
```

## Behaviour in the code

- `target_flow_definition_id`: The only way to pick the target: a flow definition id of the same organization. The worker does not resolve targets by slug.
- `payload`: Resolved as a templated object and sent as the child's `$input.data`. When the node has no `payload`, the node input is sent as is.
- `execution.timeout_ms`: Default 30000 ms in the code (the schema shows 300000, which the code does not apply). In `sync` streaming it is an idle limit, reset by every event and keep-alive, so a long child does not time out while the backend keeps the stream alive. Ignored in `async`, which uses 10 s.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Missing target_flow_definition_id` | `error` | No target workflow selected. |
| `Cannot resolve organization_id from execution state` | `error` | The run carries no organization in its state, its input or the node input. Include `organization_id` in the input when you start the run. |
| `No published version found for the target workflow` | `error` | The parent runs a published version (`prod`) but the target has none. Publish the target workflow first. |
| `Workflow chain timed out waiting for target workflow` | `error` | In `async` the dispatch took more than 10 s; on the non-streaming `sync` path the child took longer than `execution.timeout_ms`. |
| `Workflow execution failed: <detail>` | `error` | The backend could not run the child (for example, the target graph has no nodes). |

## Notes and limits

- If the `sync` stream fails (an `error` event, a close without result, or the idle limit), the worker resends the request to the non-streaming endpoint, which can start the child a second time. Design chained workflows to be safe to repeat.
- Correlation: `correlation_id` links parent and child; `root_flow_instance_result_id` is propagated unchanged through every level, so the deepest child can report the id of the entry run.
- The child's full step list is never copied into the parent: read outputs from `result.final_output_envelope.payload` and open the child run by `instance_id` for detail.
- If the target is paused for that environment, the backend answers with its pause response instead of running it.


## Contracts (JSON Schema)

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

```json
{
  "slug": "workflow.chain",
  "name": "Workflow Chain",
  "category": "workflow",
  "version": "1.0.0",
  "description": "Invokes another workflow and optionally waits for its result.\n\n  This operator enables peer-to-peer workflow chaining. It triggers a target workflow and can operate in synchronous (wait for result) or asynchronous (fire-and-forget) mode.\n\n  **Features:**\n  - **Sync Mode:** Waits for the target workflow to complete and returns its result.\n  - **Async Mode:** Fires the target workflow and continues immediately with the instance ID.\n  - **Traceability:** Correlation ID links both workflow instances for audit and debugging.\n  - **Payload Forwarding:** Define exactly what data to pass to the target workflow.\n\n  **Use Cases:**\n  - Composing complex processes from reusable workflow modules.\n  - Delegating specialized processing (e.g., validation, enrichment) to dedicated workflows.\n  - Fan-out patterns where one workflow triggers multiple independent workflows.",
  "capabilities": [
    "workflow",
    "chain",
    "composition",
    "orchestration"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "target_flow_definition_id": {
        "type": "string",
        "title": "Target Workflow",
        "description": "The workflow to invoke when this node executes.",
        "x-ui-widget": "flow-definition-picker"
      },
      "payload": {
        "type": "object",
        "title": "Payload",
        "description": "Data to send to the target workflow. Use {{expressions}} to reference upstream node outputs. If empty, the current node input ($json) is forwarded."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "mode": {
            "type": "string",
            "enum": [
              "sync",
              "async"
            ],
            "default": "sync",
            "title": "Execution Mode",
            "description": "Sync: wait for the target workflow to complete and return its result. Async: dispatch and continue without waiting."
          },
          "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
          },
          "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
          }
        }
      }
    },
    "required": [
      "target_flow_definition_id"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "target_flow_definition_id": {
        "type": "string"
      },
      "payload": {
        "type": "object"
      }
    },
    "required": [
      "target_flow_definition_id"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "instance_id": {
        "type": "string",
        "description": "The ID of the created workflow instance."
      },
      "status": {
        "type": "string",
        "description": "Final status of the target workflow (sync) or \"running\" (async)."
      },
      "result": {
        "type": "object",
        "description": "The target workflow result (sync mode only)."
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Completed",
      "description": "Target workflow completed successfully (sync) or dispatched (async).",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Target workflow failed, timed out, or could not be found.",
      "is_default": false,
      "supports_condition": true
    }
  ],
  "execution_mode": "async",
  "required_resources": [],
  "compatible_worker_pools": [
    "standard-io"
  ],
  "tags": [
    "workflow",
    "chain",
    "composition",
    "orchestration"
  ],
  "is_stateful": false,
  "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": {
    "target_flow_definition_id": {
      "type": "string",
      "title": "Target Workflow",
      "description": "The workflow to invoke when this node executes.",
      "x-ui-widget": "flow-definition-picker"
    },
    "payload": {
      "type": "object",
      "title": "Payload",
      "description": "Data to send to the target workflow. Use {{expressions}} to reference upstream node outputs. If empty, the current node input ($json) is forwarded."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "mode": {
          "type": "string",
          "enum": [
            "sync",
            "async"
          ],
          "default": "sync",
          "title": "Execution Mode",
          "description": "Sync: wait for the target workflow to complete and return its result. Async: dispatch and continue without waiting."
        },
        "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
        },
        "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
        }
      }
    }
  },
  "required": [
    "target_flow_definition_id"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "target_flow_definition_id": {
      "type": "string"
    },
    "payload": {
      "type": "object"
    }
  },
  "required": [
    "target_flow_definition_id"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "instance_id": {
      "type": "string",
      "description": "The ID of the created workflow instance."
    },
    "status": {
      "type": "string",
      "description": "Final status of the target workflow (sync) or \"running\" (async)."
    },
    "result": {
      "type": "object",
      "description": "The target workflow result (sync mode only)."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Completed",
    "description": "Target workflow completed successfully (sync) or dispatched (async).",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Target workflow failed, timed out, or could not be found.",
    "is_default": false,
    "supports_condition": true
  }
]
```
