# Traces and the span store

**Last updated:** 2026-11-26T02:16:00-03:00 (UTC-3)

The gateway already times and prices every step of a request: the routing decision, each provider attempt, the cache lookup, each guardrail and each MCP tool call. With the **span store** it keeps those steps as **spans** in its own PostgreSQL database, next to the request log, so you can open any request as a tree of timed, costed steps without running a tracing backend. Spans are W3C spans with the same trace and span IDs the gateway already exports over [OTLP](/docs/features/observability/#logs-and-traces-otlp), so the stored tree and your tracing backend line up.

The span store never holds content: no prompt, answer, tool argument or result. It holds identifiers, timing, status, tokens, the ledger cost of each step and a short allowlist of attributes per kind. Bodies stay in [content capture](/docs/features/content-capture/), under its own policy.

## Turn it on

```yaml
features:
  usage_analytics: true
  span_store: true
```

| Flag | Default | What it turns on |
| --- | --- | --- |
| `span_store` | `false` | The span store: collection on the request path, the writer, partitions, retention, the trace API and the trace drawer. Requires `usage_analytics` and PostgreSQL. An operator control, changeable at runtime from **Settings → Features** or `PUT /api/v1/admin/features/span_store` |
| `trace_explorer` | `false` | The [Traces screen and the trace detail](/docs/features/trace-explorer/) over the stored spans. Requires `span_store` |
| `analytics_store_spans` | `false` | Copies the stored spans to the [analytics store](/docs/features/analytics-store/). Requires `span_store` and the `analytics_store` block |

Spans start when the flag is turned on; nothing is backfilled. A request older than the span store keeps its [request journey](/docs/features/observability/#request-journey) as before.

### Recommended setup

Start with the shipped values: `sample_rate: 1.0` (every trace), all four `keep_always` rules, `retention_days: 14`. Watch `gateway_span_store_spans_total{result="dropped_queue_full"}` and the database size for a week. Each request writes 3 to 5 span rows (more with retries, guardrails and tools): at 100 requests per second that is roughly 26 to 43 million rows a day. If an analytics store runs next to the gateway, `spans.engine: analytics_store` takes those rows off the database entirely (see [Where spans are stored](#where-spans-are-stored) and the [measured comparison](/docs/benchmarks/span-store-engines/)). Otherwise, above about 50 requests per second sustained, lower `sample_rate` (errors, fallbacks, flagged and evaluated requests stay kept by `keep_always`) and turn on `analytics_store_spans` so long-range reads can move to the analytics store.

## What a trace holds

Each request is one **request span**; its steps are children of it. A trace groups the requests that share a W3C trace ID: requests chained by a client `traceparent`, an agent run's requests, and the calls the gateway makes to itself (a moderation guardrail, embeddings for a vector store search).

| Kind | One span per | Cost | Attributes |
| --- | --- | --- | --- |
| `request` | gateway request, the root of its steps; `subkind` is the operation | the request's valuation, or the sum of its known charge lines when the valuation is partial or unknown | route, status, attempts, `fell_back`, operation, requested model, cache kind, timeout kind, service tier, auto-route alias, blocking guardrail, stream cut, parent session, agent, `ttfb_ms`, `dropped_spans`, `valuation_reason` and the price entry (below), `traceparent: ignored_malformed` |
| `routing` | target choice of an alias | `none` | strategy that ordered the targets (`ordered`, `weighted`, `cost`, `least_busy`, `latency`, `adaptive`, `affinity`: the one the enabled feature applied, not merely the one configured), candidates, chosen target, canary side, auto-route alias; `refusal: no_eligible_target` when nothing was eligible |
| `provider_attempt` | provider send, in send order, and each target skipped before a send (an open circuit, an unhealthy target, a refused translation, a context window) | the attempt's own charge line; the whole valuation when the request made one send | `attempt`, `final`, `outcome` (`answered`, `provider_error`, `transport_failure` with no HTTP status, `skipped`), wire API, timeout kind, `sent`, skip reason; `fallback_reason` and `retry` (below), `ttfb_ms` on the final answered attempt, the generation parameters the client sent (`gen_ai.request.*`), `parameters_changed`, the price entry |
| `cache` | response-cache lookup (exact or semantic) | `none` | kind, `hit`, similarity bucket of a semantic hit |
| `guardrail` | guardrail check at the input or output stage | `none` | guardrail ID, stage, `mode` (`block`, `monitor`), outcome, findings |
| `tool` | MCP tool call or tool listing | `none` | server, configured tool name, status |
| `tool`, sub-kind `client_tool` | tool a coding agent ran itself and reported in its next request ([`agent_recognition`](/docs/features/agent-recognition/#tool-steps)) | `none` | The span is named `client tool`. `tool` (the name) and `call_id`, both only for readers with `content_structure:read` of the span's team; `reported_by: client`, `reported_error`, `agent`; no duration, never arguments or results |
| `app`, sub-kinds `transcript_turn`, `transcript_call`, `transcript_tool`, `transcript_compaction` | step of a coding agent's own transcript, uploaded with `POST /v1/traces` ([transcript ingest](/docs/features/agent-recognition/#transcript-ingest)) | `none` | `source: transcript`, `agent`; `tool` and `call_id` of a tool (its span is named `transcript tool`), both only for readers with `content_structure:read`; model and token counts of a call; never content |

- **Names** are the names the spans were exported with over OTLP: a request span is `POST /v1/chat/completions`; a model call attempt follows the GenAI convention, `{operation} {provider model}` (`chat gpt-4o-mini`), and other sends `<method> provider.<capability>` (`GET provider.containers`); a skipped target is `provider.<capability>.skipped`; a tool call `execute_tool <name>` and a tool listing `MCP operation`. Search your tracing backend by the same name. One exception: a tool a coding agent reported is exported as `execute_tool <name>` and stored as `client tool` (a transcript's as `transcript tool`), because a stored span's name is shown in every list and the name of such a tool is shown only with `content_structure:read`.
- **Why an attempt was made.** Every attempt after the first carries `fallback_reason`, what ended the step before it: `http_<status>` (`http_500`, `http_429`), `timeout`, `transport_error`, `cancelled`, or the skip reason of a skipped target (`circuit_open`); `retry: true` when the same target was sent again (a retry policy), otherwise it fell back to another target.
- **Generation parameters.** The numbers the client sent, recorded on each attempt with their OpenTelemetry names: `gen_ai.request.temperature`, `gen_ai.request.top_p`, `gen_ai.request.top_k`, `gen_ai.request.max_tokens` (`max_tokens`, `max_completion_tokens` or `max_output_tokens`), `gen_ai.request.frequency_penalty`, `gen_ai.request.presence_penalty`, `gen_ai.request.seed`, `gen_ai.request.choice.count` (`n`), and `gateway.request.reasoning_effort` (`none`, `minimal`, `low`, `medium`, `high`, `xhigh`). Gemini's `generationConfig` names map to the same keys. Text members (stop sequences, tools, messages) are content and never recorded. When a [request parameter policy](/docs/features/request-parameter-policy/) changed what an attempt sent, the attempt has `parameters_changed: true` and its `upstream_attempt` log line names the parameters. The same `gen_ai.request.*` attributes are on the exported OTLP attempt spans.
- **Price entry.** A valued step names the price that valued it (shown to readers with `prices:read` who may see the cost; for others these attributes are left out): `price.source` (the catalog, or `manual` when the [manual price book](/docs/features/pricing/) priced it), `price.override: true` when that manual price replaced an available automatic one (spans stored by earlier versions may carry `price.manual_fallback` instead), `price.input_per_million`, `price.output_per_million` (or `price.unit` and `price.unit_price` for media), `price.effective_from` and `price.model`; the request span also has `valuation_reason` (for example `text_token_estimate`).
- **Events.** Spans carry up to 16 events, each `{"name", "time", "attributes"}`: `attempt_failed` (outcome, `http_status` or `cause`, timeout kind), `retry` and `fallback` (reason), `target_skipped` (reason), and on the request span `refused` (the gateway's `error_code` and HTTP status, for a 4xx refusal other than a client's 499), `quota_refused` (policy, dimension, reset time, and the limit for the caller's own ceiling) and `traceparent_ignored`. Events are gateway facts, never provider bodies or stack traces.
- **Helper calls** (a guardrail's moderation call, embeddings) are `request` spans with `origin: helper`, children of the request that made them. `origin` also marks the gateway's own traffic: `evaluation` (judges), `experiment` (experiment items), `playground` (evaluator tests), `shadow` (canary shadow copies); client traffic is `app`.
- The kinds `judge` and `app` are reserved: judge runs and application spans received over OTLP are stored by later releases.
- **Timing** is exact to the microsecond (`started_at`, `duration_us`). Local (pattern) guardrails run in one scan of the text and share its duration; provider and extension guardrails are timed one by one. A streamed answer's output guardrails span the relay.
- **Cost** comes from the ledger the gateway already writes ([usage valuation](/docs/features/usage-valuation/) and [charge lines](/docs/features/usage-valuation/)): `cost_state` is `known`, `partial`, `unknown` or `none` (a step that costs nothing). Unknown is never zero. The attempts' known amounts add up to the request's known amount.
- **Tokens** are what the provider reported; a missing count is unknown, never zero.
- **Status:** a request span is `error` for a 5xx, a cut stream or a refusal the gateway made (a 4xx other than 499 with its own `error_code`, such as `model_forbidden`, `quota_exceeded` or `guardrail_blocked`; such a request is not kept by the `error` keep rule, which follows 5xx); an attempt for a failed send or an error status; a skipped target is `unset`. The exported OTLP server span keeps the HTTP convention (a 4xx leaves the status unset) and carries `error.type`; an answer cut after it started is an error there too, with `gateway.stream_cut` (`provider`, `client` or `gateway`); a provider cut has `error.type: stream_interrupted`, and the stored request span carries the cut's `error_code` (`stream_interrupted`, `stream_aborted` or `client_closed_stream`). A provider's own error answer relayed to the client has `error_code: upstream_http_error` on the stored request span (its body is never copied).
- **Identity.** Every span carries the request's key, principal, team and, with `organizations` on, `organization_id`: the whole hierarchy, so a span joins up to its tenant without a lookup. The exported OTLP spans carry the same as `gateway.key.id`, `gateway.principal`, `gateway.team.id` and `gateway.organization.id`, and every log line of the request has `key_id`, `principal`, `team` and `organization_id` next to `request_id`, `trace_id` and `span_id`.
- **Configuration** (flag `trace_explorer`). The request span carries `config_fingerprint`, `config_version`, `policy_revisions` and, for a translated request, `translation_lossy`: which configuration and which policies served the request, as hashes and names, never a value ([configuration at the time](/docs/features/trace-explorer/#configuration-at-the-time)). A replay's request span carries `replay_of`.
- **Structural items** (flag `span_structural_items`, off by default). The request span can record the shape of the conversation without any of its text: one bounded `structure` attribute with the number of messages, their roles in order, the tools declared and the tool calls by name, attachment counts by type and the token split. The exported OTLP server span carries the same as `gateway.structure.*`. It is for teams that capture no content, and it is shown only to readers with `content_structure:read` of the span's team; the fields and bounds are in [content capture](/docs/features/content-capture/#structural-items-on-the-span-span_structural_items).
- Each request span carries the request's key, principal, session, end user, customer and usage tags, so later filters need no join. [End-user erasure](/docs/features/metadata-retention/) removes the end user (or customer member) from their spans and summaries, and, when the job completes, from the analytics store copy, including spans the database has already dropped.

### Trace IDs and the caller's trace

The trace ID is the W3C trace ID the gateway used and propagated; the span IDs are the ones exported over OTLP. `spans.caller_trace` decides what happens when a client sends `traceparent`:

- `join` (default): the gateway continues the caller's trace. The request span's parent is the caller's span and `trace_source` is `caller`, so the client's own spans and the gateway's form one tree.
- `link`: the gateway mints its own trace ID, keeps the caller's in `caller_trace_id` and `caller_parent_span_id` and adds a `caller` link on the request span. Choose it when clients you do not control could send other teams' trace IDs: a client can then never attach its requests to a trace it does not own. The response's `traceparent` header names the gateway's trace. The exported OTLP server span carries a span link to the caller's span, so an OpenTelemetry backend still joins the two traces without putting the gateway's spans inside the caller's; `request_id`/`correlation_id` stay the same in both.

Either way every read filters by team first: a W3C trace that crosses teams shows each reader only their own team's spans and never counts the others. An organization administrator reads the teams of its organization only, so another organization's spans in a shared trace stay invisible.

A `traceparent` that does not parse is ignored: the request starts a trace of its own, its request span has `traceparent: ignored_malformed` and a `traceparent_ignored` event, and its `request` log line has `traceparent: ignored_malformed`.

## Settings

All settings sit in the `spans` block of the gateway YAML. The first ten are the **runtime policy**: `PUT /api/v1/admin/span-store/settings` or the console's **Span store** panel replaces them as a whole, and they apply from the next request on every replica after its configuration refresh. The last five are the writer's engine and capacity, read once at startup.

```yaml
spans:
  sample_rate: 1.0 # 0-1 head sampling by trace (keyed hash of the trace id; every span of a trace kept or dropped together)
  keep_always: [error, fallback, guardrail_flagged, evaluated] # stored even when sampled out; [] keeps only the sample
  retention_days: 14 # 1-3650 daily partitions kept; never longer than an active metadata_retention
  max_spans_per_request: 64 # 1-1024; extra steps are counted on the request span (dropped_spans)
  max_spans_per_trace: 2000 # 1-100000; a batch for a trace at the bound is dropped and counted (dropped_trace_limit)
  max_attribute_bytes: 2048 # 256-16384 per span's attributes; longest values are dropped first
  caller_trace: join # join: continue the caller's W3C trace id; link: mint a gateway trace id and keep the caller's apart
  log_link_template: "" # https URL with {trace_id}, {span_id}, {request_id}, {caller_trace_id}: "Open in logs" in the trace drawer
  apm_link_template: "" # same placeholders: "Open in APM"
  retained_max_traces: 10000 # 0-1000000 annotated traces copied past retention into gateway_spans_retained
  # engine: database # database | analytics_store; unset derives it: analytics_store when the analytics_store block is configured, else database (see "Where spans are stored")
  queue_size: 8192 # 64-1048576 requests waiting; when full, a request's spans are dropped and counted, never awaited
  batch_size: 500 # 1-10000 spans per write (COPY plus one upsert of the touched trace summaries and one of the sessions); 5000 by default with engine analytics_store
  flush_interval: 1s # 100ms-1m between writes when the batch is not full
  max_connections: 2 # 1-16 database connections of the writer's own pool
```

| Setting | Default | Bounds | Applies | What it does |
| --- | --- | --- | --- | --- |
| `spans.sample_rate` | `1` | 0–1 | next request | Head sampling of traces by a keyed hash of the trace ID: every span of a trace is kept or dropped together, and every replica decides alike. `0` keeps only what `keep_always` keeps |
| `spans.keep_always` | `[error, fallback, guardrail_flagged, evaluated]` | any of the four, each once | next request | Stores a request even when sampling dropped its trace: `error` (HTTP 5xx, a cut stream or a failed provider attempt), `fallback` (served after a move to another target, or by a semantic fallback), `guardrail_flagged` (a guardrail blocked or masked, or a monitor would have), `evaluated` (captured for live evaluation). `[]` keeps only the sample |
| `spans.retention_days` | `14` | 1–3650 | next maintenance pass (hourly) | A span is kept at least this many days: a day's partition is dropped whole once the whole day is older than the retention. Never longer than an active [metadata retention](/docs/features/metadata-retention/): the shorter one applies |
| `spans.max_spans_per_request` | `64` | 1–1024 | next request | Spans of one request, its request span included; further steps are counted in the request span's `dropped_spans` attribute |
| `spans.max_spans_per_trace` | `2000` | 1–100000 | next write | Counted from the trace summary, in the same statement that updates it: once a trace holds this many spans, its later spans are dropped and counted as `dropped_trace_limit`. A trace below the bound takes one whole batch, so it can end up to one batch over it |
| `spans.max_attribute_bytes` | `2048` | 256–16384 | next request | Encoded size of one span's attributes; the longest values are dropped first and `attributes_truncated` is set |
| `spans.caller_trace` | `join` | `join`, `link` | next request | Continue the caller's trace, or keep the caller's IDs apart (see above) |
| `spans.log_link_template` | `""` | empty or an https URL (http only for a loopback host), at most 1024 bytes | next read | **Open in logs** in the trace drawer. The only braces allowed are `{trace_id}`, `{span_id}`, `{request_id}` and `{caller_trace_id}`, each replaced URL-escaped with the root request's values. The gateway's stdout and OTLP log lines already carry `trace_id` and `span_id` |
| `spans.apm_link_template` | `""` | same | next read | **Open in APM**, for example `https://apm.example.com/trace/{caller_trace_id}` |
| `spans.retained_max_traces` | `10000` | 0–1000000 | next maintenance pass | Annotated traces kept past retention (see below); `0` keeps none |
| `spans.engine` | derived: `analytics_store` when the `analytics_store` block is configured (and `analytics_store.spans_retention_days` is unset), else `database` | `database`, `analytics_store` | restart | Where the writer puts spans and every span read answers from: the database (PostgreSQL), or the [analytics store](/docs/features/analytics-store/) (ClickHouse). `analytics_store` requires the `analytics_store` block and refuses `analytics_store.spans_retention_days` (see [Where spans are stored](#where-spans-are-stored)) |
| `spans.queue_size` | `8192` | 64–1048576 | restart | Requests waiting to be written. When the queue is full a request's spans are dropped and counted (`dropped_queue_full`); the request never waits |
| `spans.batch_size` | `500`, or `5000` with `engine: analytics_store` | 1–10000 | restart | Spans per write. The analytics store wants few large inserts (about one per second per table), so its default is larger; a value you set wins |
| `spans.flush_interval` | `1s` | 100ms–1m | restart | Pause before writing a batch that is not full |
| `spans.max_connections` | `2` | 1–16 | restart | Connections of the writer's own database pool, apart from the request path's, so span writes never take a connection a request waits for. With `engine: analytics_store` the pool only reads the ledger of a request that did not carry its cost (rare) |
| `analytics_store.spans_retention_days` | `90` | 1–3650 | restart | How long the analytics store keeps copied spans, as a table TTL (see below). Only for the copy (`engine: database`) |

**API.** `GET /api/v1/admin/span-store/settings` (`config:read`) returns the policy in force (`spans`), the stored override or `null`, the YAML base with defaults (`yaml`), the source of each setting (`default`, `yaml` or `console`), the writer's settings with their sources and the retention applied. `PUT /api/v1/admin/span-store/settings` (`features:manage`, CSRF) takes `{"version": <current>, "spans": {...every setting...}}`: a partial policy, an unknown or null member or a value out of bounds is refused naming the setting, and a stale version answers `409`. `DELETE /api/v1/admin/span-store/settings` with `{"version": <current>}` removes the override and returns to the YAML. Both writes are audited (`span_store.set`, `span_store.revert`).

## Where spans are stored

`spans.engine` chooses where the span writer puts spans and where every span read answers from. Choose it at deploy time; the measured comparison is in [Span store engines](/docs/benchmarks/span-store-engines/). When it is unset, the gateway derives it at startup and logs `span_engine_derived` once: the analytics store when the `analytics_store` block is configured, so span rows, about a quarter of the WAL and most of the disk leave PostgreSQL; otherwise the database. Setting `analytics_store.spans_retention_days` (the copy's own retention) keeps the database engine and its copy. An explicit `spans.engine` always wins. `GET /span-store` reports the source as `derived` (owner, 2026-11-23).

- **`database` (default):** spans, summaries and the retained table live in PostgreSQL, as described on this page. This needs nothing besides the database. It suits most deployments up to a few hundred requests per second; above that the span rows become a large share of the database's writes.
- **`analytics_store`:** the writer sends each batch straight to the [analytics store](/docs/features/analytics-store/) (ClickHouse), so the database writes no span rows at all. Use it when the analytics store already runs next to the gateway and span volume would weigh on the database. It requires the `analytics_store` block; the gateway refuses to start without it.

What stays the same with `analytics_store`:
- **The request path:** one non-blocking send to the same bounded queue. When the analytics store is down or slow, batches fail and are dropped and counted (`dropped_write_failed`, `last_error` such as `analytics_store_unreachable` or `analytics_store_timeout`), the writer pauses a second after each failure, the queue fills, and further spans are dropped and counted (`dropped_queue_full`). Once the store answers again the writer resumes on its own; spans dropped meanwhile are not written later. Requests never wait and never fail because of it.
- **The API:** `GET /traces/{trace_id}`, the span read, `GET /requests/{id}/trace`, the journey's `stored_trace` and `span_state`, `/span-store` and the summary rebuild keep their contract; trace reads say `source: analytics_store`. Team and organization filters run inside every analytics store query, before any bound. When the analytics store cannot be read, the trace, span and request reads and the rebuild answer `503 analytics_store_unavailable`, never that the spans are gone; `/span-store` still answers with the writer's counters and `storage.unavailable: analytics_store_unavailable`, so the drops during an outage stay visible.
- **What stays in PostgreSQL:** the request log, the ledger (costs, charge lines, receipts), keys and authorization. A span's cost still comes from the ledger the request wrote; only a request whose usage write failed has its ledger read back from the database.

How the analytics store holds them:
- **Tables:** spans go to `gateway_spans_v1` (the copy's table; the engine's rows have `copy_id` 0), one summary row per trace and batch to `gateway_trace_summaries_v1` (sorted by trace), folded on read with the same rules as the database's summaries, and annotated traces to `gateway_spans_retained_v2`. The gateway creates them; the shipped ClickHouse user's grants are enough.
- **Retention:** a table TTL equal to the retention in force (`spans.retention_days`, never longer than an active metadata retention), moved by the hourly pass when it changes. ClickHouse removes expired rows during its background merges, so they can stay readable for a few hours past the cutoff. Annotated traces are copied to the retained table within a day of expiring, up to `spans.retained_max_traces`.
- **Erasure:** a completed end-user erasure is applied within about 30 seconds with lightweight deletes: each labelled span is written again without the label and the labelled row is deleted; the summary rows likewise.
- **`max_spans_per_trace`:** read from the summary rows before each batch. Two replicas writing the same trace at once can each let one batch through past the bound.

Switching the engine moves no data. Spans written before the switch stay where they were until that engine's retention removes them. With `analytics_store`, a trace or request with no span in the analytics store is still read from the database (`source` says which); a trace with spans on both sides of the switch shows the analytics store's part only. Back on `database`, traces only the analytics store holds are read from it only with `analytics_store_spans` on, as copied traces. The span copy (`analytics_store_spans`) only runs with `engine: database`; with `analytics_store` the flag has nothing to copy.

## How spans are written

On the request path the gateway only appends a small fixed struct per step to the request's recorder and, once it has answered and written the usage row, makes one non-blocking send of the recorder to the writer's queue. With `span_store` off nothing is collected and the request path does no added work: zero added allocations. With it on a request adds one allocation of about 1.1 KiB (the recorder, which holds two steps inline and the generation parameters; a request with more steps, a fallback for example, adds one more) and the enqueue. Measured numbers: see [Performance](/docs/performance/method/#span-store-request-path-cost).

Everything else runs on one writer goroutine per replica: sampling and `keep_always`, span names and attributes, the ledger costs, then one transaction per batch: one upsert statement for every touched trace summary (which also applies `max_spans_per_trace`), a `COPY` of the spans, and one upsert statement for the touched session summaries. The ledger costs come from the valuation and charge lines the request itself just wrote, carried to the writer with its spans, so the writer reads nothing back; only when that usage write failed, or found the event already written, does the writer read the usage event, its valuation and its charge lines from the database (counted in `gateway_span_store_ledger_reads_total`). Either way the cost is the stored ledger's: unknown stays unknown, never zero. Each statement has a 5-second timeout. A failed write drops that batch, counts it (`dropped_write_failed`) and pauses the writer for a second, so a database outage fills the queue and drops beyond it instead of retrying without bound. At shutdown the writer writes what its queue still holds within a 3-second window ([shutdown](/docs/operate/shutdown/)); anything left is dropped.

Spans live in `gateway_spans`, range-partitioned by UTC day of `started_at`. The writer and an hourly maintenance pass create today's partition and the next two days' ahead of time; replicas serialize on a database lock, so several replicas never race on the same partition.

## Retention

Once a day's partition ends more than `spans.retention_days` ago, the maintenance pass drops it whole (so a span is kept at least that long): no row-by-row delete. Before it drops one, the spans of **annotated traces** (a person scored one of its requests, or put it in a review queue) are copied into `gateway_spans_retained`, up to `spans.retained_max_traces` traces; a trace read finds them there (`retained: true`). When the retained table is full the pass logs `span_retained_table_full` and drops the rest. Trace and session summaries last updated before the cutoff are deleted with their partition, unless their trace is retained.

## Trace and session summaries

The writer keeps one summary row per team and trace (`gateway_trace_summaries`) and per team and session (`gateway_session_summaries`), in the same transaction as the spans:

- **Trace:** first and last instant, the root request (span, request ID, name, origin), counts of spans, requests, LLM calls, tool calls, errors, cache hits, guardrail flags and dropped spans, `fell_back`, the cost (state and known amount, combined: known plus unknown is `partial`), input and output tokens, up to 16 models, session and end user.
- **Session:** first and last instant, traces, requests, cost, tokens, end user, parent session, first trace and up to 16 agents.

Summaries are derived data. `POST /api/v1/admin/traces/summaries/rebuild` (`analytics:rebuild`, global administrators) takes the query parameters `from` and `to`, the first and last UTC day as `YYYY-MM-DD` (at most 31 days apart; default the last 7 days), and recomputes the summaries of every trace with a span in those UTC days, and of every session they touch, from the stored spans.

## Read traces

| Route | Permission | What it returns |
| --- | --- | --- |
| `GET /api/v1/admin/traces/{trace_id}` | `logs:read` | The trace's spans in your teams, oldest first (at most 2000, `truncated` when more exist), the summary when every returned span belongs to one team, `retained`, `valuation_shown`, `links` (the filled link templates) and `source` (`database`, or `analytics_store`, below) |
| `GET /api/v1/admin/traces/{trace_id}/spans/{span_id}` | `logs:read` | One span and its `capture_state`: `not_captured`, `audit_only` or `evaluation`, with `capture_id` on the span. It says whether [content capture](/docs/features/content-capture/#one-policy-for-audit-and-evaluation-content_capture_evaluation) kept the request's content and whether judges may read it (needs `content_capture_evaluation`; `not_captured` otherwise). The request span carries the same two values as attributes, on both span engines, and the drawer shows them as *Content*. With `span_structural_items` the span's `structure` attribute is returned to readers with `content_structure:read` of its team and left out for anyone else. The `tool` and `call_id` attributes of a `client_tool` or `transcript_tool` span follow the same rule, here and in the trace read above |
| `GET /api/v1/admin/requests/{id}/trace` | `logs:read` | The stored trace ID and request span of a request ID (the latest one of a reused ID), and `source` |
| `GET /api/v1/admin/span-store` | `config:read` | This replica's writer counters, the partitions with row estimates, retained traces, the write lag (`write_lag_seconds`: this replica's latest batch, from the end of its oldest request to the commit), the retention applied, the policy in force, the writer settings and, with `analytics_store_spans`, the copy state |
| `POST /api/v1/admin/traces/summaries/rebuild` | `analytics:rebuild` | Rebuilds summaries (above) |

Team roles read only their live memberships' spans, filtered in SQL before the 2000 bound; a missing and an out-of-scope trace or request ID answer the same `404`.

### When a request has no spans

The request log row is the durable anchor: it is never sampled and outlives the span retention, so a read that finds no spans tells you why, in the `404`'s `error.code`, the journey's `span_state` and its gaps:

| `error.code` | Journey `span_state` | Meaning |
| --- | --- | --- |
| `spans_expired` | `expired` | Older than `spans.retention_days`: the partition was dropped. The request log row, ledger and receipts remain |
| `spans_sampled_out` | `sampled_out` | Dropped by `spans.sample_rate`, judged with the rate in force now. A request the request log shows a keep rule kept (a 5xx or more than one attempt for `error`, more than one attempt for `fallback`, a blocking guardrail for `guardrail_flagged`) is never called sampled out; a guardrail monitor flag or a live evaluation capture is not on the request log row, so such a request whose spans were dropped reads as sampled out |
| `trace_not_found` | `not_stored` | Served before the span store was on, its spans dropped (counted in `gateway_span_store_spans_total`), or not visible to you |

With `analytics_store_spans` on, a trace the database's retention already dropped is read from the analytics store copy, which keeps spans for `analytics_store.spans_retention_days`: the answer has `source: analytics_store` and no summary, and the drawer marks it. The copy is read with the same team filter, in its query. When the copy cannot be read, `GET /traces/{trace_id}` and `GET /requests/{id}/trace` answer `503 analytics_store_unavailable` rather than saying the spans are gone (an analytics store user without `ALTER ADD COLUMN` on an older span table makes every such read fail this way). With `engine: database`, `GET /traces/{trace_id}/spans/{span_id}` reads the database only; with `engine: analytics_store` every read answers from the analytics store. Fields follow the request log's flags: tags with `usage_tags`, session with `session_tracking`, end user with `end_user_tracking`, and cost with `usage_valuation` plus `analytics:read`. Every answer is `Cache-Control: private, no-store`.

A fallback request, read by a reader who may see cost:

```json
{
  "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
  "summary": {"spans": 4, "requests": 1, "llm_calls": 2, "errors": 1, "fell_back": true, "cost_state": "partial", "cost_usd": "0.00002", "root_request_id": "req-1", "models": ["chat-flaky"], "origin": "app"},
  "spans": [
    {"span_id": "b7ad6b7169203331", "parent_span_id": "00f067aa0ba902b7", "trace_source": "caller", "kind": "request", "subkind": "chat", "name": "POST /v1/chat/completions", "origin": "app", "request_id": "req-1", "duration_us": 912410, "status": "ok", "http_status": 200, "model": "chat-flaky", "cost_state": "partial", "cost_usd": "0.00002", "attributes": {"attempts": 2, "fell_back": true, "route": "POST /v1/chat/completions", "status": 200}},
    {"span_id": "0b7d1c9f3a5e2a10", "parent_span_id": "b7ad6b7169203331", "kind": "routing", "name": "route chat-flaky", "duration_us": 41, "status": "ok", "cost_state": "none", "attributes": {"candidates": 2, "chosen_target": "primary", "strategy": "ordered"}},
    {"span_id": "5c1f7e0a9d3b4c21", "parent_span_id": "b7ad6b7169203331", "kind": "provider_attempt", "attempt": 1, "name": "provider.attempt primary model-a", "duration_us": 301877, "status": "error", "http_status": 500, "provider": "primary", "cost_state": "unknown", "attributes": {"attempt": 1, "final": false, "outcome": "provider_error", "sent": true}},
    {"span_id": "9e4a2b6c8d0f1e32", "parent_span_id": "b7ad6b7169203331", "kind": "provider_attempt", "attempt": 2, "name": "provider.attempt backup model-b", "duration_us": 598210, "status": "ok", "http_status": 200, "provider": "backup", "input_tokens": 10, "output_tokens": 5, "cost_state": "known", "cost_usd": "0.00002", "attributes": {"attempt": 2, "final": true, "outcome": "answered", "sent": true}}
  ],
  "truncated": false,
  "retained": false,
  "valuation_shown": true,
  "links": {}
}
```

## In the console

- **Request details** (from a request log row) shows **Open trace** only when the request's spans can be read, and otherwise says why (expired, sampled out, not stored); each request log row has a trace button while `span_store` is on.
- The **request journey** shows **Open trace** when the request has stored spans, and then no longer lists the gaps spans cover (stage timing, per-attempt detail and timing, guardrails that passed, spans only in a tracing backend). Without them it offers no trace and its gap says why. The journey API returns `stored_trace` with the trace and span ID and its `source`, and `span_state`.
- The **trace drawer** names the trace type (*Single request*, *Request chain* for requests sharing a caller's trace, *Agent run*, *Judge trace*, *Application trace*) with a legend of the span kinds present, then the summary (duration, spans, requests, LLM calls, errors, fallback, cache hits, guardrail flags, cost with *partial* when a step is unpriced, tokens), then a tree of spans: kind, name, a duration bar placed on the trace's time line, status and cost. Selecting a span shows its timing, status, model and provider, tokens, cost, attributes and events. With [evaluation results](/docs/features/evaluation-results/) on, a span that was judged shows an eval count in the tree and lists its results in its panel. **Open in logs** and **Open in APM** appear when their templates are set. On a phone (below 768 px) the span panel stacks under the tree.
- With `trace_explorer` on, the **Traces** screen lists traces and spans over one query bar, and a trace opens everywhere in the fuller trace detail (tree, time-ruled waterfall, agent graph, and the span tabs Span, Evaluations, Feedback, Logs and Annotations) instead of this drawer: see [Trace explorer](/docs/features/trace-explorer/).
- The **Span store** panel on the **Logs** page (`config:read`) shows the writer's counters and the partitions, the retention kept and where it comes from, and edits the runtime policy (`features:manage`); every setting shows its source (`default`, `YAML` or `console`), and the writer's settings are shown read-only, each with its source, and a restart note.

## Metrics

With [`metrics_endpoint`](/docs/features/observability/#metrics-prometheus), `/metrics` (and the [OTLP metrics](/docs/features/observability/#otlp-metrics) push) carries the writer's series, per replica:

| Series | Type | Labels | Measured |
| --- | --- | --- | --- |
| `gateway_span_store_spans_total` | counter | `kind` (`request`, `routing`, `provider_attempt`, `cache`, `guardrail`, `tool`, and `judge` once [evaluation tracing](/docs/features/evaluation-tracing/) stored a judge span), `result` | Spans by what became of them: `written`, `sampled_out`, `dropped_queue_full`, `dropped_write_failed`, `dropped_trace_limit` |
| `gateway_span_store_queued_requests_total` | counter | — | Requests whose spans entered the queue |
| `gateway_span_store_queue_depth` | gauge | — | Requests waiting in the queue |
| `gateway_span_store_batches_total` | counter | `result` (`ok`, `failed`) | Batch writes |
| `gateway_span_store_ledger_reads_total` | counter | — | Requests whose costs the writer read back from the ledger because the request did not carry them (its usage write failed or was a repeat); near zero in normal operation |
| `gateway_span_store_write_seconds` | histogram | — | One batch write: partitions, ledger costs, `COPY` and summaries |

Alert on `rate(gateway_span_store_spans_total{result=~"dropped_.*"}[5m]) > 0`: spans are being lost (a full queue or a failing database), never requests.

## Analytics store copy

With `analytics_store_spans` and the [`analytics_store`](/docs/features/analytics-store/) block, the spans are copied to the analytics store's `gateway_spans_v1` table by the same copy as the usage events: a cursor over a copy sequence, gap ranges for identifiers committed out of order, and a change log for updates while the copy is on; a completed end-user erasure is applied to the copy directly, so it also reaches spans past the database's retention. The table is ordered by team, start time, trace and span, and keeps spans for `analytics_store.spans_retention_days` (default 90) as a table TTL, longer than the database's `spans.retention_days` if you choose. A dropped database partition is not a change: the copy keeps its spans. Single-trace reads answer from PostgreSQL, and from the copy only once the database no longer holds the trace (see [When a request has no spans](#when-a-request-has-no-spans)). The copy state is in `GET /api/v1/admin/span-store` (`analytics_copy`). The copied table carries the organization, the caller's parent span, the events and the links too.

## Upgrade and downgrade

- Migration 197 adds `gateway_spans` (partitioned, no partition yet), `gateway_spans_retained`, the two summary tables, the settings override and the span copy state. Migration 198 adds the `organization_id` column to the request log rows and the spans; older rows keep none. Nothing is backfilled. An existing analytics store span table gets its new columns (`organization_id`, `caller_parent_span_id`, `events`, `links`) when the copy starts, which needs `ALTER ADD COLUMN` on the database ([analytics store](/docs/features/analytics-store/)).
- Rolling upgrade: replicas of the older release ignore the new tables. Turn the flag on once every replica runs this release.
- Downgrade: turn `span_store` off first. The older binary refuses a database migrated by a newer release; restore the backup taken before the upgrade, as for any release.

## See also

- [Trace explorer](/docs/features/trace-explorer/): the Traces screen, the query, facets and the trace detail.
- [Agent runs](/docs/features/agent-recognition/): coding-agent runs recognized from the requests, whose steps are these spans; a recognized request span carries a `run` attribute block.
- [Observability](/docs/features/observability/): logs, OTLP traces, request journey and metrics.
- [Evaluation results](/docs/features/evaluation-results/): results attached to spans, as span events and over OTLP.
- [Judge calls as linked, labelled traffic](/docs/features/evaluation-tracing/): judge runs as their own traces with a `judge` span, linked both ways to the judged span.
- [Usage valuation](/docs/features/usage-valuation/): where span costs come from.
- [Analytics store](/docs/features/analytics-store/) and [metadata retention](/docs/features/metadata-retention/).

## Application spans

With `otlp_ingest` an application sends its own OpenTelemetry spans to `POST /v1/traces`, and they join the gateway's spans of the same trace as spans of kind `app`: the gateway's request appears under the application's model call. See [application spans over OTLP](/docs/features/otlp-ingest/). Keys read traces with the [public trace API](/docs/features/public-trace-api/).
