# Deduplicate

> Filters duplicate payloads based on a derived key and time window.

Source: https://docs.sommatic.ai/en/nodes/ops.dedupe/

- Slug: `ops.dedupe`
- Family: Operations
- Version: 1.0.0
- Status: Experimental. Always fails today: the worker calls `logger.debug`, which the runtime logger does not provide, and the error is not caught, so the whole run fails. `ttl_ms` is never applied either.
- Execution: sync

Filters duplicate payloads based on a derived key and time window.

This operator ensures that specific events are processed only once within a given timeframe. It is crucial for handling "at-least-once" delivery systems where duplicate messages might occur (e.g., Queue retries, Webhook replays).

**Behavior:**
- Calculates a unique key from the input payload (via template/expression).
- Checks if the key exists in the cache.
- **Unique:** If new, passes to 'unique' port and caches key.
- **Duplicate:** If exists, passes to 'duplicate' port (or drops).

**Use Cases:**
- Ignorning double-clicks on a "Submit" button.
- Processing a specific webhook ID only once.

## Configuration

- `key_template` (string, required, accepts expressions): Expression that produces the dedupe key, e.g. `{{ $json.messageId }}`. `payload` is not a variable of the expression engine, so `{{payload.messageId}}` never resolves and every run shares the same literal key.
- `ttl_ms` (number, optional): Window duration to remember keys. Default: `3600000`.

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

- `unique` (default): First time seen.
- `duplicate`: Already seen within TTL.
- `error`: Error

## Input contract

- `payload` (object, optional)

## Output contract

- `payload` (object, optional)

## In expressions

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

- `$("Deduplicate").item.json.payload` (object) **The worker does not return it: reads as undefined.**
- `$("Deduplicate").item.json.messageId` (string) = `"msg_8f2a"` (Not suggested by the editor)
- `$("Deduplicate").item.json.subject` (string) = `"Invoice 1042"` (Not suggested by the editor)


## How it works

Meant to route an item to `unique` the first time a key is seen and to `duplicate` afterwards, using the workflow key-value state. In the current runtime it throws `logger.debug is not a function` before the check, so the run fails.

1. Resolves `key_template` as an expression and merges the input item with the config (config wins).
2. Throws `Missing 'key_template'` when the key is empty.
3. Builds the state key `dedupe:<key_template>`.
4. Calls `logger.debug()`, which throws; the worker does not catch it, so the run fails. The steps below are not reached today.
5. Looks the key up in `$input.$kv_state`: found → `duplicate`; not found → `unique`, saving the key with the current time in milliseconds through `meta.kv_state`. Both pass the input item through unchanged.

## In a workflow

### Node

```json
{
  "node_id": "node-dedupe-mail",
  "label": "Skip repeated emails",
  "operator_slug": "ops.dedupe",
  "operator_version": "1.0.0",
  "config": {
    "key_template": "{{ $json.messageId }}",
    "ttl_ms": 3600000
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "unique",
  "data": {
    "messageId": "msg_8f2a",
    "subject": "Invoice 1042"
  },
  "meta": {
    "kv_state": {
      "dedupe:msg_8f2a": 1795705445000
    }
  }
}
```

## Output ports (behaviour in the code)

### `unique`

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

```json
{
  "messageId": "msg_8f2a",
  "subject": "Invoice 1042"
}
```

### `duplicate`

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

```json
{
  "messageId": "msg_8f2a",
  "subject": "Invoice 1042"
}
```

### `error`

Never emitted: failures throw instead, which fails the run.

## Behaviour in the code

- `key_template`: Resolved once as node config: `{{ $json.messageId }}` works, `{{payload.messageId}}` does not (it stays literal, so every run shares one key). Mixed text such as `mail:{{ $json.messageId }}` gives a string key.
- `ttl_ms`: Read but never applied: a key, once saved, would stay a duplicate indefinitely.

## 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. Thrown on every run: the run fails. |
| `Missing 'key_template'` | `error` | `key_template` is set neither on the node nor in the input item. Thrown: the run fails. |

## 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.
- Even once fixed, two items with the same key in the same run would both be `unique`, because writes are saved only after the run ends.
- A thrown error fails the whole run with `Node <node_id> (<slug>) failed: <message>` and edges from `error` do not fire. Inside a `flow.try` scope the engine sends it to the catch node instead.
- 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.dedupe",
  "name": "Deduplicate",
  "category": "ops",
  "version": "1.0.0",
  "description": "Filters duplicate payloads based on a derived key and time window.\n\n  This operator ensures that specific events are processed only once within a given timeframe. It is crucial for handling \"at-least-once\" delivery systems where duplicate messages might occur (e.g., Queue retries, Webhook replays).\n\n  **Behavior:**\n  - Calculates a unique key from the input payload (via template/expression).\n  - Checks if the key exists in the cache.\n  - **Unique:** If new, passes to 'unique' port and caches key.\n  - **Duplicate:** If exists, passes to 'duplicate' port (or drops).\n\n  **Use Cases:**\n  - Ignorning double-clicks on a \"Submit\" button.\n  - Processing a specific webhook ID only once.",
  "capabilities": [
    "filter",
    "dedupe",
    "reliability"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "key_template"
    ],
    "properties": {
      "key_template": {
        "type": "string",
        "title": "Dedupe Key",
        "format": "expression",
        "description": "Expression that produces the dedupe key, e.g. `{{ $json.messageId }}`. `payload` is not a variable of the expression engine, so `{{payload.messageId}}` never resolves and every run shares the same literal key."
      },
      "ttl_ms": {
        "type": "number",
        "default": 3600000,
        "title": "TTL (ms)",
        "description": "Window duration to remember keys."
      },
      "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": {
      "payload": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "description": "Passes original payload.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "unique",
      "label": "Unique",
      "is_default": true,
      "description": "First time seen."
    },
    {
      "port_id": "duplicate",
      "label": "Duplicate",
      "description": "Already seen within TTL."
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "filter",
    "dedupe",
    "idempotency"
  ],
  "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": [
    "key_template"
  ],
  "properties": {
    "key_template": {
      "type": "string",
      "title": "Dedupe Key",
      "format": "expression",
      "description": "Expression that produces the dedupe key, e.g. `{{ $json.messageId }}`. `payload` is not a variable of the expression engine, so `{{payload.messageId}}` never resolves and every run shares the same literal key."
    },
    "ttl_ms": {
      "type": "number",
      "default": 3600000,
      "title": "TTL (ms)",
      "description": "Window duration to remember keys."
    },
    "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": {
    "payload": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "Passes original payload.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "unique",
    "label": "Unique",
    "is_default": true,
    "description": "First time seen."
  },
  {
    "port_id": "duplicate",
    "label": "Duplicate",
    "description": "Already seen within TTL."
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
