# Start Trace Span

> 启动一个新的分布式追踪 Span，实现深度可观测性。

Source: https://docs.sommatic.ai/zh/nodes/ops.trace.start/

- 标识: `ops.trace.start`
- 类别: 运维
- 版本: 1.0.0
- 状态: 可用
- 执行方式: sync

启动一个新的分布式追踪 Span，实现深度可观测性。

Span 让你能够在追踪瀑布图中直观查看特定工作块的耗时和细节。该算子会启动一个自定义 span，通常需要由对应的“End Span”关闭（或在工作流结束时自动关闭）。

**适用场景：**
- 显式测量某一组步骤的耗时。
- 为追踪片段添加业务专属属性（标签）。
- 通过 Parent Trace ID 与外部系统关联。

## 配置

- `name` (string, 必填): 该 span 阶段的可读名称。

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

## 输出端口

- `success` (默认): Span 已激活。
- `error`: 启动追踪器失败。

## 输入契约

- `attributes` (object, 可选): 附加到 span 的自定义标签/属性。
- `parent_trace_id` (string, 可选): 可选：关联到外部追踪。

## 输出契约

- `trace_id` (string, 可选)
- `span_id` (string, 可选)

## 在表达式中

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

- `$("Start Trace Span").item.json.trace_id` (string) = `"94d2f2da-7886-4e23-8bbb-b8c841d99b21"`
- `$("Start Trace Span").item.json.span_id` (string) = `"50cb8ce0-8949-4f60-a5ff-7795654af4d7"`
- `$("Start Trace Span").item.json.port` (string) = `"success"` (编辑器不提示)


## 工作原理

生成 trace id 和 span id，向编排器日志写入一行 `[TRACE-START] <name>`，并返回这两个 id。不会调用任何追踪后端。

1. 将输入项与解析后的配置合并（配置优先）。
2. 若设置了 `parent_trace_id` 则用作 trace id，否则生成 UUID v4。
3. `name` 为空时以 `Missing 'name'` 从 `error` 输出。
4. 生成 span id（UUID v4），并以 info 级别记录 `[TRACE-START] <name>`；随附的 id 和 `attributes` 不会写入。
5. 返回 `{ port: "success", trace_id, span_id }`；引擎把整个对象作为输出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-trace-start-checkout",
  "label": "Start checkout span",
  "operator_slug": "ops.trace.start",
  "operator_version": "1.0.0",
  "config": {
    "name": "checkout"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "success",
  "data": {
    "port": "success",
    "trace_id": "94d2f2da-7886-4e23-8bbb-b8c841d99b21",
    "span_id": "50cb8ce0-8949-4f60-a5ff-7795654af4d7"
  }
}
```

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

### `success`

已设置 `name`。

```json
{
  "port": "success",
  "trace_id": "94d2f2da-7886-4e23-8bbb-b8c841d99b21",
  "span_id": "50cb8ce0-8949-4f60-a5ff-7795654af4d7"
}
```

### `error`

`name` 为空。

```json
{
  "port": "error",
  "error": "Missing 'name'"
}
```

## 代码中的行为

- `parent_trace_id`: 不在配置 schema 中（仅出现在输入契约中），但会从节点配置读取；节点上未设置时从输入项读取：`parent_trace_id`、`attributes`。
- `attributes`: 可以传入，但不会写到任何地方：日志行只包含名称。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing 'name'` | `error` | 节点和输入项中都没有设置 `name`。 |

## 说明与限制

- 这些 id 不会自动传递，也不会与运行 id 关联。请显式传递，例如在 `ops.trace.end` 中使用 `{{ $json.trace_id }}` 和 `{{ $json.span_id }}`。
- 运行时 logger 只输出消息文本，随附的结构化对象不会写入日志。
- Worker 把字段直接放在顶层而不是 `data` 中，因此引擎把整个返回对象（包括 `port`）作为节点输出。
- 从 `error` 端口输出不会使运行失败：引擎沿 `error` 上的连线继续；若没有连线，该分支直接结束。
- `execution` 设置（`retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail`、`timeout_ms`）可以填写，但本 worker 和引擎都不会应用。


## 契约（JSON Schema）

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

```json
{
  "slug": "ops.trace.start",
  "name": "Start Trace Span",
  "category": "ops",
  "version": "1.0.0",
  "description": "Initiates a new Distributed Tracing Span for deep observability.\n\n  Spans allow you to visualize the duration and details of a specific block of work in a trace waterfall graph. This operator starts a custom span, which must typically be closed by a corresponding 'End Span' (or happens automatically at workflow end).\n\n  **Use Cases:**\n  - Explicitly measuring the duration of a specific group of steps.\n  - Adding business-specific attributes (tags) to a trace segment.\n  - Correlating with external systems via Parent Trace ID.",
  "capabilities": [
    "observability",
    "tracing",
    "apm"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "name"
    ],
    "properties": {
      "name": {
        "type": "string",
        "title": "Span Name",
        "description": "Human-readable name for the span phase."
      },
      "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": {
      "attributes": {
        "type": "object",
        "description": "Custom tags/attributes to attach to the span."
      },
      "parent_trace_id": {
        "type": "string",
        "description": "Optional: Link to an external trace."
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "description": "The created trace context identifiers.",
    "properties": {
      "trace_id": {
        "type": "string"
      },
      "span_id": {
        "type": "string"
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Started",
      "is_default": true,
      "description": "Span active."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Failed to start tracer."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "observability",
    "tracing",
    "telemetry"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_vectry",
    "profile": {
      "name": "Vectry Analytics",
      "verified": true,
      "url": "https://me.veripass.com/vectry",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "required": [
    "name"
  ],
  "properties": {
    "name": {
      "type": "string",
      "title": "Span Name",
      "description": "Human-readable name for the span phase."
    },
    "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": {
    "attributes": {
      "type": "object",
      "description": "Custom tags/attributes to attach to the span."
    },
    "parent_trace_id": {
      "type": "string",
      "description": "Optional: Link to an external trace."
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "The created trace context identifiers.",
  "properties": {
    "trace_id": {
      "type": "string"
    },
    "span_id": {
      "type": "string"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Started",
    "is_default": true,
    "description": "Span active."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Failed to start tracer."
  }
]
```
