# Write State

> Persists a value to the persistent state store.

Source: https://docs.sommatic.ai/en/nodes/ops.state.write/

- Slug: `ops.state.write`
- Family: Operations
- Version: 1.0.0
- Status: Experimental. Always fails today: the worker calls `logger.debug`, which the runtime logger does not provide, so every run leaves through `error` with "logger.debug is not a function". Do not use it until it is fixed. Writes in `instance` scope and `ttl_ms` are not applied either.
- Execution: async

Persists a value to the persistent state store.

This operator allows workflows to remember information across different execution steps, or even share data between different workflows (using Global scope).

**Scopes:**
- **Instance:** Visible only to this workflow run.
- **Case:** Visible to all workflows in the same Case/Thread.
- **Global:** Visible system-wide (use with caution).

**Use Cases:**
- Saving a user's progress.
- Caching an API token.
- Passing data from a parent workflow to a child workflow via 'Case' scope.

## Configuration

- `scope` (string, required): Visibility level of the stored variable. Default: `instance`. Allowed values: `instance`, `case`, `global`.

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): State saved successfully.
- `error`: Database/Storage failure.

## Input contract

- `key` (string, required): Variable Name/Key
- `value` (any, optional): Data to store (Any JSON serializable)
- `ttl_ms` (number, optional): Time-to-Live in milliseconds

## Output contract

- `value` (any, optional): The stored value confirmation.

## In expressions

What a later node can read from this node's output with `$("Write State").item.json.<path>` (write your node's label instead of `Write State`). **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.

- `$("Write State").item.json.value` (any) = `"2026-11-26T15:04:05.000Z"`: The stored value confirmation.


## How it works

Meant to store a value under `key` in the run (`instance`) or in the workflow key-value state (`global`, `case`). In the current runtime it always leaves through `error` with `logger.debug is not a function`, so nothing is written.

1. Merges the input item with the resolved config (config wins).
2. Uses `scope` (default `instance`) and leaves through `error` with `Missing 'key'` when `key` is empty.
3. Calls `logger.debug()`, which throws; the worker catches it and leaves through `error`. The steps below are not reached today.
4. `global` / `case`: returns `{ value }` on `success` and asks the backend to save it under `<key>` or `case:<key>` through `meta.kv_state`.
5. `instance`: returns `{ _state_update, value, port }`, which the engine does not apply: the run variables do not change.

## In a workflow

### Node

```json
{
  "node_id": "node-save-last-sync",
  "label": "Save last sync time",
  "operator_slug": "ops.state.write",
  "operator_version": "1.0.0",
  "config": {
    "scope": "global",
    "key": "last_sync_at",
    "value": "{{ $now }}"
  }
}
```

### Envelope

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

## Output ports (behaviour in the code)

### `success`

Not reached in the current runtime: the `logger.debug()` call fails first. Shown with the shape the code builds.

```json
{
  "value": "2026-11-26T15:04:05.000Z"
}
```

### `error`

Every run today. The output is the whole returned object, `{ port, error }`.

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

## Behaviour in the code

- `key`: Not in the config schema (only in the input contract), but read from the node config or, when unset there, from the input item: `key`, `value`, `ttl_ms`.
- `ttl_ms`: Only logged; it is never applied.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `logger.debug is not a function` | `error` | The worker calls `logger.debug()`, which the runtime logger does not provide. It happens on every run; there is no configuration that avoids it. |
| `Missing 'key'` | `error` | `key` is set neither on the node nor in the input item. |

## Notes and limits

- The worker calls `logger.debug()`, which the runtime logger does not provide (it offers `info`, `warning`, `error`, `log` and `success`). The call throws on every run.
- Key-value state lives in the workflow definition metadata (`kv_state`), shared by every run of that workflow. The backend injects it at run start as `$input.$kv_state` only when the run uses the draft graph; runs of a published version receive none. Writes (`meta.kv_state` of each step) are merged into the metadata after the run ends, so later nodes of the same run do not see them. There is no expiry.
- To keep a value for later nodes of the same run, use the node output instead: downstream nodes read it with `{{ $json.<field> }}` or by node name.
- Leaving through `error` does not fail the run: the engine follows the edges wired to `error`, and if there are none the branch simply ends.
- 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": "ops.state.write",
  "name": "Write State",
  "category": "ops",
  "version": "1.0.0",
  "description": "Persists a value to the persistent state store.\n\n  This operator allows workflows to remember information across different execution steps, or even share data between different workflows (using Global scope).\n\n  **Scopes:**\n  - **Instance:** Visible only to this workflow run.\n  - **Case:** Visible to all workflows in the same Case/Thread.\n  - **Global:** Visible system-wide (use with caution).\n\n  **Use Cases:**\n  - Saving a user's progress.\n  - Caching an API token.\n  - Passing data from a parent workflow to a child workflow via 'Case' scope.",
  "capabilities": [
    "state",
    "persistence",
    "store"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "scope"
    ],
    "properties": {
      "scope": {
        "type": "string",
        "enum": [
          "instance",
          "case",
          "global"
        ],
        "default": "instance",
        "title": "State Scope",
        "description": "Visibility level of the stored variable."
      },
      "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": "Variable Name/Key"
      },
      "value": {
        "type": "any",
        "description": "Data to store (Any JSON serializable)"
      },
      "ttl_ms": {
        "type": "number",
        "description": "Time-to-Live in milliseconds"
      }
    },
    "required": [
      "key"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "value": {
        "type": "any",
        "description": "The stored value confirmation."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Success",
      "is_default": true,
      "description": "State saved successfully."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Database/Storage failure."
    }
  ],
  "execution_mode": "async",
  "tags": [
    "state",
    "database",
    "persistence"
  ],
  "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 of the stored variable."
    },
    "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": "Variable Name/Key"
    },
    "value": {
      "type": "any",
      "description": "Data to store (Any JSON serializable)"
    },
    "ttl_ms": {
      "type": "number",
      "description": "Time-to-Live in milliseconds"
    }
  },
  "required": [
    "key"
  ]
}
```

### output_contract_schema

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

### ports

```json
[
  {
    "port_id": "success",
    "label": "Success",
    "is_default": true,
    "description": "State saved successfully."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Database/Storage failure."
  }
]
```
