# Begin Saga

> Initiates a distributed transaction using the Saga pattern.

Source: https://docs.sommatic.ai/en/nodes/saga.begin/

- Slug: `saga.begin`
- Family: Operations
- Version: 1.0.0
- Status: Experimental. Returns a `saga_id` and a `_context_update` object that the execution engine never reads: no saga scope is registered and no compensation is tracked.
- Execution: sync

Initiates a distributed transaction using the Saga pattern.

The Saga pattern manages long-running transactions by breaking them into a sequence of sub-transactions. If any step fails, the Saga orchestrator executes compensating transactions (undo steps) to rollback the changes and maintain eventual consistency.

This operator marks the beginning of a Saga scope. It initializes a unique Saga ID and tracks the transaction steps.

**Key Concepts:**
- **Steps:** A sequence of actions ("do") and their rollbacks ("undo").
- **Compensation:** The reverse action triggered on failure.
- **Traceability:** All actions in the scope are linked by "saga_id".

**Use Cases:**
- E-commerce order processing (Inventory -> Payment -> Shipping).
- Booking travel (Flight -> Hotel -> Car).

## Configuration

- `rollback_on` (array<string>, optional): List of error codes or statuses that should trigger an automatic rollback execution. Default: `["ERROR","FAILURE"]`.

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

- `success` (default): Saga initialized successfully.
- `error`: Failed to initialize Saga.

## Input contract

- `steps` (array<object>, optional): Ordered list of steps defining execution and compensation logic.

## Output contract

- `saga_id` (string, optional): Unique Transaction ID
- `status` (string, optional)

## In expressions

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

- `$("Begin Saga").item.json.saga_id` (string) = `"ce78b34b-0bf5-4372-89b0-ae0eb6adddc1"`: Unique Transaction ID
- `$("Begin Saga").item.json.status` (string) = `"active"`
- `$("Begin Saga").item.json.port` (string) = `"success"` (Not suggested by the editor)
- `$("Begin Saga").item.json._context_update` (object) = `{…}` (Not suggested by the editor)
- `$("Begin Saga").item.json._context_update.saga` (object) = `{…}` (Not suggested by the editor)


## How it works

Experimental. Generates a `saga_id` (UUID v4), logs `[SAGA-BEGIN]` and returns the id with a `_context_update` object that the engine ignores: no saga scope is registered and no compensation is tracked.

1. Merges the input item with the resolved config (config wins).
2. Uses `rollback_on` (default `["ERROR", "FAILURE"]`) and `steps` (default `[]`).
3. Generates `saga_id` and logs `[SAGA-BEGIN] Starting Saga <saga_id> with <n> steps.` at info level.
4. Returns `{ port: "success", saga_id, status: "active", _context_update }`; the engine uses that whole object as the output and does not read `_context_update`.

## In a workflow

### Node

```json
{
  "node_id": "node-begin-order-saga",
  "label": "Begin order saga",
  "operator_slug": "saga.begin",
  "operator_version": "1.0.0",
  "config": {
    "rollback_on": [
      "ERROR",
      "FAILURE"
    ],
    "steps": [
      {
        "name": "reserve_stock",
        "undo": {
          "action": "release_stock"
        }
      }
    ]
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "success",
  "data": {
    "port": "success",
    "saga_id": "ce78b34b-0bf5-4372-89b0-ae0eb6adddc1",
    "status": "active",
    "_context_update": {
      "saga": {
        "id": "ce78b34b-0bf5-4372-89b0-ae0eb6adddc1",
        "steps": [
          {
            "name": "reserve_stock",
            "undo": {
              "action": "release_stock"
            }
          }
        ],
        "rollback_on": [
          "ERROR",
          "FAILURE"
        ],
        "history": []
      }
    }
  }
}
```

## Output ports (behaviour in the code)

### `success`

Always, in practice.

```json
{
  "port": "success",
  "saga_id": "ce78b34b-0bf5-4372-89b0-ae0eb6adddc1",
  "status": "active",
  "_context_update": {
    "saga": {
      "id": "ce78b34b-0bf5-4372-89b0-ae0eb6adddc1",
      "steps": [
        {
          "name": "reserve_stock",
          "undo": {
            "action": "release_stock"
          }
        }
      ],
      "rollback_on": [
        "ERROR",
        "FAILURE"
      ],
      "history": []
    }
  }
}
```

### `error`

Only if an unexpected exception occurs while building the result.

```json
{
  "port": "error",
  "error": "<message>"
}
```

## Behaviour in the code

- `steps`: Not in the config schema (only in the input contract), but read from the node config or the input item. The steps are only copied into `_context_update`; nothing executes `do` or `undo`.
- `rollback_on`: Copied into `_context_update`; nothing evaluates it.

## Notes and limits

- Missing for a working saga: the engine does not read `_context_update`, keeps no saga scope, records no step history and never runs `undo` steps. `saga.compensate` cannot find the saga from the context either.
- If you use the id, pass it on explicitly with `{{ $json.saga_id }}`. Model rollbacks today with `flow.try` and explicit compensation nodes.
- The worker returns its fields at the top level instead of under `data`, so the engine uses the whole returned object, `port` included, as the node output.
- The `execution` settings (`retryOnFail`, `maxTries`, `waitBetweenTries`, `continueOnFail`, `timeout_ms`) are accepted, but neither this worker nor the engine applies them.


## Contracts (JSON Schema)

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

```json
{
  "slug": "saga.begin",
  "name": "Begin Saga",
  "category": "ops",
  "version": "1.0.0",
  "description": "Initiates a distributed transaction using the Saga pattern.\n\n  The Saga pattern manages long-running transactions by breaking them into a sequence of sub-transactions. If any step fails, the Saga orchestrator executes compensating transactions (undo steps) to rollback the changes and maintain eventual consistency.\n\n  This operator marks the beginning of a Saga scope. It initializes a unique Saga ID and tracks the transaction steps.\n\n  **Key Concepts:**\n  - **Steps:** A sequence of actions (\"do\") and their rollbacks (\"undo\").\n  - **Compensation:** The reverse action triggered on failure.\n  - **Traceability:** All actions in the scope are linked by \"saga_id\".\n\n  **Use Cases:**\n  - E-commerce order processing (Inventory -> Payment -> Shipping).\n  - Booking travel (Flight -> Hotel -> Car).",
  "capabilities": [
    "saga",
    "transaction",
    "ops",
    "consistency"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "rollback_on": {
        "type": "array",
        "items": {
          "type": "string"
        },
        "default": [
          "ERROR",
          "FAILURE"
        ],
        "title": "Rollback Triggers",
        "description": "List of error codes or statuses that should trigger an automatic rollback execution."
      },
      "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": {
      "steps": {
        "type": "array",
        "description": "Ordered list of steps defining execution and compensation logic.",
        "items": {
          "type": "object",
          "properties": {
            "name": {
              "type": "string",
              "description": "Step Name"
            },
            "do": {
              "type": "object",
              "description": "Logic to execute"
            },
            "undo": {
              "type": "object",
              "description": "Logic to compensate"
            }
          },
          "required": [
            "name",
            "undo"
          ]
        }
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "saga_id": {
        "type": "string",
        "description": "Unique Transaction ID"
      },
      "status": {
        "type": "string"
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Success",
      "is_default": true,
      "description": "Saga initialized successfully."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Failed to initialize Saga."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "saga",
    "transaction",
    "consistency"
  ],
  "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": {
    "rollback_on": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "default": [
        "ERROR",
        "FAILURE"
      ],
      "title": "Rollback Triggers",
      "description": "List of error codes or statuses that should trigger an automatic rollback execution."
    },
    "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": {
    "steps": {
      "type": "array",
      "description": "Ordered list of steps defining execution and compensation logic.",
      "items": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "description": "Step Name"
          },
          "do": {
            "type": "object",
            "description": "Logic to execute"
          },
          "undo": {
            "type": "object",
            "description": "Logic to compensate"
          }
        },
        "required": [
          "name",
          "undo"
        ]
      }
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "saga_id": {
      "type": "string",
      "description": "Unique Transaction ID"
    },
    "status": {
      "type": "string"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Success",
    "is_default": true,
    "description": "Saga initialized successfully."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Failed to initialize Saga."
  }
]
```
