# OTEL spans & exporter wiring (/docs/otel-observability)



OTel spans are one surface in the **observability**
[thematic island](/docs/concept-clusters#what-lives-outside-the-cluster-pattern) —
siblings of [observability](/docs/observability) (the orientation page),
[lineage](/docs/lineage), and [runtime inspector](/docs/runtime-inspector).

This page is the read-side OTel surface. For the write-side audit
ledger that the `llm.invocation` span sits beside, see
[Audit ledger](/docs/audit-ledger).

This page covers the span types the substrate emits, the
parent ids that nest them correctly, the auto-flush
knob, the `runtime.spans` in-process introspection facet, and a
minimal OTLP exporter wiring. For non-OTel observability —
structured logs, Prometheus, Datadog statsd, lifecycle-event
streaming — see [Observability](/docs/observability).

**Subpath:** `@pleach/core/otel`

## The span types [#the-span-types]

The core span types are `session.turn`, `graph.stage`,
`llm.invocation`, and `tool.execution`. Two more appear only when
their trigger happens: `llm.attempt` under a retried model call, and
`subagent.run` around a sub-agent. Every other span in your trace
tree is either a parent (your HTTP handler) or a child that you
wired yourself.

| Span type        | Where emitted                                                                                                                                                                                                   | Key attributes                                                                                                                                                                                                             |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `session.turn`   | Around `runtime.executeMessage` for one user turn                                                                                                                                                               | `pleach.session_id`, `pleach.turn_id`, `pleach.tenant_id`, `pleach.actor_kind`                                                                                                                                             |
| `llm.invocation` | One per logical LLM call through a seam, one per provider request the tool loop sends, and one per sub-agent model call                                                                                         | `pleach.model_id`, `pleach.family`, `pleach.call_class`, `pleach.tokens.input`, `pleach.tokens.output`, `pleach.tenant_id`; on a sub-agent call also `pleach.subagent.id`, `pleach.subagent.depth`, `pleach.subagent.step` |
| `llm.attempt`    | One per provider dispatch of a seam call that dispatched more than once (primary stream, empty-stream retries, reasoning re-ask), as children of its `llm.invocation`. A call that dispatched once has no child | The parent's attributes plus `pleach.attempt.index` (the dispatch's `modelCall.attemptIndex`)                                                                                                                              |
| `subagent.run`   | One per `spawnAgent` child run, kind `host.custom`                                                                                                                                                              | `pleach.subagent.id`, `pleach.subagent.depth` (1 = spawned by the top-level turn), `pleach.tenant_id`                                                                                                                      |
| `graph.stage`    | Around each orchestrator stage transition                                                                                                                                                                       | `pleach.stage_id` (`anchor-plan` / `tool-loop` / `synthesize` / `post-turn`), `pleach.session_id`, `pleach.turn_id`                                                                                                        |
| `tool.execution` | Per tool dispatch — pairs with the `tool.completed` stream event                                                                                                                                                | `pleach.tool_name`, `pleach.capability_id`, `pleach.status`, `pleach.duration_ms`                                                                                                                                          |

These are the cardinality-correct seams. `llm.attempt` has its own
kind, so a count of `llm.invocation` spans stays one per logical call.
Count the `modelCall` audit rows for billed dispatches. Retries a provider makes inside one stream call are one
dispatch here. Adding your own per-call span at a custom seam
double-counts against `llm.invocation` and clutters the trace tree.

A failed sub-agent model call records a fixed error message, never
the provider's error text. A sub-agent span cut short by a user Stop
is not marked as an error; it carries `pleach.aborted: true`. A
timeout or failure sets status `error`.

The span names are exported, so consumers match on constants instead
of string literals:

```typescript
import { PLEACH_SPAN_NAMES, PLEACH_ATTRIBUTE_KEYS } from "@pleach/core/otel";

PLEACH_SPAN_NAMES.LLM_INVOCATION; // "llm.invocation"
PLEACH_SPAN_NAMES.LLM_ATTEMPT;    // "llm.attempt"
PLEACH_SPAN_NAMES.SUBAGENT_RUN;   // "subagent.run"
PLEACH_ATTRIBUTE_KEYS.ATTEMPT_INDEX; // "pleach.attempt.index"
```

## Parent ids [#parent-ids]

Spans nest naturally: a `session.turn` parents the `graph.stage`s
fired during that turn; each `graph.stage` parents the
`llm.invocation`s and `tool.execution`s emitted during that stage.
A retried `llm.invocation` parents its `llm.attempt`s.

A sub-agent stays in the parent's trace. Its `subagent.run` span
nests under the spawning turn's open `graph.stage` (else its
`session.turn`), and each child model call is an `llm.invocation`
under that `subagent.run`.

`@pleach/core` imports nothing from `@opentelemetry/*`, so it does
not touch the OTel context API. Each span names its parent by id:
`PleachSpanStart.parentId` is the `id` of the handle the runtime got
from your exporter for the parent. Your bridge maps that id to the
parent span (the recipe below does). If your bridge starts a span
with no `parentId` under the active OTel context, and your HTTP
handler opens its own outer span, `session.turn` nests under that —
the chain reads
`http.request → session.turn → graph.stage → llm.invocation` end
to end.

Calls made through a seam (utility, decision, synthesize) each get
an `llm.invocation` span, and so does each provider request the tool
loop sends from the graph's LLM executor. When such a call retries
through a provider that records every attempt, each provider request
gets an `llm.attempt` child span tagged `pleach.attempt.index` and
`pleach.attempt.site`. A call that sent one request keeps its single
`llm.invocation` span.

A sub-agent run by the built-in tool-loop executor gets a
`subagent.run` span under the spawning turn's open stage, and each
model call the sub-agent makes nests under it. A host-supplied
sub-agent executor gets no `subagent.run` span unless it reads the
trace context it is handed.

Spans still don't pair one to one with ledger rows: a row written
from a framework adapter's observed call has no `llm.attempt` span.

## `graph.stage` bills to dispatch, not report [#graphstage-bills-to-dispatch-not-report]

The superstep engine computes two stage values per superstep and
keeps them apart. The *reporting* value drives the stage-transition
breadcrumb and the lattice-conformance verdict; it is aware of the
prior stage and may be deliberately demoted purely to expose a
defect. The `graph.stage` span does not bill to it.

The span opens on the *dispatch* value — a pure function of the
triggered node set, computed with no reference to the prior stage.
Billing a span to the reporting value would attribute real work,
real time, and real errors to a stage chosen for diagnosis; a
span's `pleach.stage_id` is the stage the superstep's work actually
belongs to. If a trace and a stage-transition log disagree about a
superstep's stage, the trace is the attribution surface and the log
is the diagnostic one — that disagreement is by design, not drift.

## Auto-flush [#auto-flush]

The exporter buffer flushes on a turn cadence. The knob lives on
`SessionRuntimeConfig`:

```typescript
import { SessionRuntime } from "@pleach/core";

const runtime = new SessionRuntime({
  storage: memoryAdapter,
  userId: "user-123",
  otelFlushIntervalTurns: 1,   // default: flush every turn
});
```

Default is `1` — the buffer drains at the end of every
`session.turn`. Raise it (`5`, `10`) to batch in
high-throughput deployments where the per-turn flush cost shows
up in tail latency. Set it to `0` to disable the runtime-driven
flush entirely and let the SDK's batch processor drive cadence on
its own timer.

## `runtime.spans` facet [#runtimespans-facet]

The `runtime.spans` facet is the in-process handle on the wired
exporter. It exposes the exporter lifecycle — `start(input)` to open
a host span, `flush()` to drain buffered snapshots, `shutdown()` to
close the exporter — plus three introspection reads:

```typescript
import { SessionRuntime } from "@pleach/core";

const runtime = new SessionRuntime({ /* ... */ });
await runtime.executeMessage(sessionId, "hello");

runtime.spans.inFlightCount();   // number — spans started but not yet ended
runtime.spans.isShutdown();      // boolean — has the exporter been shut down?
runtime.spans.snapshot();        // → { inFlightCount: number; isShutdown: boolean }
```

`snapshot()` returns the exporter's lifecycle state, **not** the span
records — it's `{ inFlightCount, isShutdown }`, a single read of the
two introspection counters. Calling `.find(...)` on it throws; it is
not an array. The default `NoopOtelExporter` tracks both counters
accurately even when no sink is wired.

To READ the emitted span records in-process — for test assertions or
a DevTools trace-tree panel — wire the reference `CapturingOtelExporter`
and read its `captured` array directly. It captures every span
snapshot in memory instead of forwarding to an external collector:

```typescript
import { SessionRuntime } from "@pleach/core";
import { CapturingOtelExporter } from "@pleach/core/otel";

const exporter = new CapturingOtelExporter();
const runtime = new SessionRuntime({ /* ... */, otelExporter: exporter });
await runtime.executeMessage(sessionId, "hello");

const turnSpan = exporter.captured.find((s) => s.name === "session.turn");
// each captured span is a PleachSpanSnapshot:
// {
//   name: string;
//   kind: "session.turn" | "llm.invocation" | "llm.attempt"
//       | "graph.stage" | "tool.execution" | "host.custom";
//   id: string;
//   parentId: string | undefined;
//   attributes: Record<string, unknown>;   // includes the pleach.* keys
//   status: "ok" | "error" | "unset";
//   error: Error | undefined;
//   startTimeNs: bigint;   // epoch nanoseconds
//   endTimeNs: bigint;
//   durationNs: bigint;
// }
```

Span times are epoch nanoseconds. In Node the clock is monotonic,
advanced by `process.hrtime` from a one-time epoch anchor, so a
duration never runs backwards. An `llm.attempt` span is emitted with
explicit start and end times (`PleachSpanStart.startTimeNs` and
`end(endTimeNs)`), because the first attempt is only known to be one
once a second dispatch starts.

`CapturingOtelExporter` is the test/DevTools sink. Production hosts
wire a real sink adapter instead — see the recipe below.

## Exporter substrate and a minimal OTLP recipe [#exporter-substrate-and-a-minimal-otlp-recipe]

`@pleach/core` has zero `@opentelemetry/*` imports. It emits its
spans through one contract — `OtelExporter` — and nothing else.
The runtime does **not** read the global tracer provider. If
`config.otelExporter` is omitted, the runtime uses the default
`NoopOtelExporter`, which drops every span. A NodeSDK started
alongside the runtime captures no pleach spans on its own.

So a real OTLP pipeline needs two pieces: the OTel SDK (configures
the destination and registers a tracer provider) **and** a small
bridge that implements `OtelExporter` against `@opentelemetry/api`,
passed to the runtime as `config.otelExporter`. The bridge lives in
your host code (or a `@pleach/observe` destination) — it's the
only part that imports the OTel SDK.

```typescript
import { NodeSDK } from "@opentelemetry/sdk-node";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import { trace, context, SpanStatusCode, type Span } from "@opentelemetry/api";
import { SessionRuntime } from "@pleach/core";
import type {
  OtelExporter,
  PleachSpanStart,
  PleachSpanHandle,
} from "@pleach/core/otel";

// 1. Configure and start the OTel SDK. This registers a tracer
//    provider and points the OTLP exporter at your collector.
const sdk = new NodeSDK({
  traceExporter: new OTLPTraceExporter({
    url: process.env.OTLP_ENDPOINT,                // e.g. https://api.honeycomb.io/v1/traces
    headers: {
      "x-honeycomb-team": process.env.HONEYCOMB_API_KEY ?? "",
    },
  }),
});
sdk.start();

// 2. Bridge @pleach/core's OtelExporter contract to @opentelemetry/api.
//    This is the only file that imports the OTel SDK; core never does.
const tracer = trace.getTracer("@pleach/core");

// Pleach times are epoch nanoseconds; OTel takes [seconds, nanoseconds].
const toHrTime = (ns: bigint): [number, number] => [
  Number(ns / 1_000_000_000n),
  Number(ns % 1_000_000_000n),
];

class OtelApiExporter implements OtelExporter {
  // Open spans by the id handed back to the runtime, so a child's
  // parentId resolves to its OTel parent.
  private open = new Map<string, Span>();

  startSpan(start: PleachSpanStart): PleachSpanHandle {
    const parent = start.parentId ? this.open.get(start.parentId) : undefined;
    const ctx = parent ? trace.setSpan(context.active(), parent) : context.active();
    const span = tracer.startSpan(
      start.name,
      {
        attributes: { ...start.attributes },      // carries pleach.tenant_id, pleach.family, …
        startTime: start.startTimeNs !== undefined ? toHrTime(start.startTimeNs) : undefined,
      },
      ctx,
    );
    const id = crypto.randomUUID();
    this.open.set(id, span);
    return {
      id,
      setAttribute: (k, v) => span.setAttribute(k, v as never),
      setAttributes: (attrs) => span.setAttributes(attrs as never),
      setStatus: (status, error) =>
        span.setStatus({
          code: status === "error" ? SpanStatusCode.ERROR : SpanStatusCode.OK,
          message: error?.message,
        }),
      recordError: (error) => {
        span.recordException(error);
        span.setStatus({ code: SpanStatusCode.ERROR });
      },
      end: (endTimeNs) => {
        this.open.delete(id);
        span.end(endTimeNs !== undefined ? toHrTime(endTimeNs) : undefined);
      },
    };
  }
  async flush(): Promise<void> {
    /* the SDK's batch processor drains on its own timer */
  }
  async shutdown(): Promise<void> {
    await sdk.shutdown();
  }
}

// 3. Wire the bridge into the runtime. WITHOUT this, spans fall to the
//    default NoopOtelExporter and go nowhere.
const runtime = new SessionRuntime({
  storage: memoryAdapter,
  userId: "user-123",
  otelExporter: new OtelApiExporter(),
});
```

The bridge is destination-agnostic: the same `OtelApiExporter` lands
in Honeycomb, Datadog's OTLP intake, Grafana Tempo, and any
self-hosted OpenTelemetry Collector — only the OTLP `url` and auth
headers in step 1 differ. For Datadog APM, point `OTLP_ENDPOINT` at
the agent's OTLP intake (`http://localhost:4318/v1/traces` by
default). For Tempo or a self-hosted Collector, point at the
collector's OTLP HTTP receiver.

## `pleach.tenant_id` attribute [#pleachtenant_id-attribute]

Every span carries `pleach.tenant_id` when `runtime.tenant` is
configured, or when an outbound HTTP call rides through the
`withTenantHeader` adapter. The attribute is set at span-start
from the active tenant context, so it appears on every span type
without per-call wiring on your side.

This is the load-bearing field for per-tenant trace queries — the
Honeycomb / Tempo / Datadog query `WHERE pleach.tenant_id = $1`
gives you a tenant's full trace history without joining to the
audit ledger. See [Tenant facet](/docs/tenant-facet).

## The emit contract [#the-emit-contract]

Two things hold for the span surface:

1. A turn emits one of each of the four span types to an in-process
   exporter.
2. The noop default — no exporter wired, no SDK started — stays
   noop. Span construction allocates nothing and no records buffer
   on a process-global.

## What not to do [#what-not-to-do]

* Don't add wall-clock timestamps as span attributes. Spans carry
  their own timing via `startTimeUnixNano` / `endTimeUnixNano`;
  a second clock disagrees with the first about subtle things
  (NTP skew, monotonic vs wall).
* Don't emit your own per-call span at a custom seam. The
  `llm.invocation` span is the cardinality-correct one — one per
  logical model call (seam calls and the tool loop's requests), with one `llm.attempt` child per provider
  dispatch when the call was retried. A custom span at a
  provider-wrapper site double-counts; a span in a stream observer
  fires per chunk and floods the trace tree.
* Don't share a single OTLP exporter across worker processes
  without configuring the SDK for it. The default batch processor
  isn't fork-safe; each worker needs its own `NodeSDK.start()`
  after the fork, or the parent's exporter ends up holding spans
  the workers emit.
* Don't disable `pleach.tenant_id` to "reduce cardinality." It's
  the join key every tenant-scoped trace query reads. Cardinality
  control belongs at the exporter's sampler, not at the attribute
  source.

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="Observability" href="/docs/observability" description="Lifecycle events, structured logging, Prometheus, Datadog, Honeycomb — the non-OTel observability surface." />

  <Card title="Lineage" href="/docs/lineage" description="Cross-session dependency graph — joins to spans on `pleach.session_id`." />

  <Card title="Audit ledger" href="/docs/audit-ledger" description="The write-side ledger row, including rows from framework adapters that have no span." />

  <Card title="Tenant facet" href="/docs/tenant-facet" description="The `runtime.tenant` configuration that stamps `pleach.tenant_id` onto every span." />

  <Card title="Facets" href="/docs/facets" description="The in-process introspection surface that `runtime.spans` is part of." />
</Cards>
