---
title: "Observability for LLM Applications"
book: observability-for-llm-applications
edition: 2026.11.2
verified: 2026-11-23
edition_code: W9DX-M10H
canonical: https://rollingedition.com/observability-for-llm-applications
license: CC BY-NC 4.0
more_permissions: https://rollingedition.com/policies/reuse
attribution: "Observability for LLM Applications, Edition 2026.11.2, examples passed Nov 23, 2026. By Rolling Edition, https://rollingedition.com/observability-for-llm-applications. Text CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/), with added permissions (https://rollingedition.com/policies/reuse). Code MIT, copyright Rolling Edition and contributors. Written with AI. Verified by people."
---
Edition 2026.11.2. Examples passed Nov 23, 2026. 80 of 80 examples pass. Written with AI. Verified by people.

To cite a section, name Edition 2026.11.2 and link to the section's permanent link: https://rollingedition.com/observability-for-llm-applications/s/{section_id}

# Trace a request, then ask where its time went

By the end of this chapter you can build one message's trace by hand, print it as a tree, and say where its time and tokens went. You can then do the same sums over a day of messages and say which step takes the most.

Ambrewick is a personal assistant app's back end, written for this book. A user sends a message, and the assistant answers it from its knowledge base, from a tool, or with a fixed reply. Its log keeps one line for each message and one for each reply, and nothing between them. On the dev day, the twenty messages of 2026-12-07 that this chapter replays, the slowest message was message 3271. It took 36,230.7 ms from arrival to reply. Message 809 is the first one this chapter traces. It reads "brew coffee at noon", and its time from arrival to reply is 11,520.7 ms. The log cannot say how that time divided between choosing a route, searching the knowledge base and writing the answer. A trace records that division, one timed step at a time.

## One message, one trace {#one-message-one-trace}

A trace is kept per message because that is the unit a question about a user's experience is asked about. Someone who asks why message 809 was slow needs its steps together, and someone who asks where the day's time went needs the traces of all twenty messages side by side. A log line per event cannot be grouped that way without a key, and the [trace ID](#spans-by-hand) is that key. Every span of one message carries it, so the two questions are one query each, not a search through text.

A trace is the record of one user message's work: every span made for it, sharing one trace ID. Their parent links join them into a tree, and a span whose parent is missing still belongs to the trace. A span is a named, timed operation with attributes and a parent, except the root, which has none. The root covers the whole message, and each step the assistant takes is a span beneath it, with its own start and end.

The Agent Harnesses book also keeps a record of each step, and it calls that record a trace. There a trace is a file with one JSON object per line, the transcript of one run of an agent, as [One line per event](https://rollingedition.com/agent-harnesses/s/one-line-per-event) describes. Here a trace is OpenTelemetry's spans, one trace per message, and its tree is made of parent links. The two books agree on what a trace is for, and they differ in form.

Ambrewick handles a message in up to five steps. The route step makes one model call that picks one of seven routes. Three of the routes, `messages`, `devices` and `media`, search the knowledge base before answering, and that search is the retrieve step. The answer step makes a model call that writes the reply. An answer call may ask for a tool instead of replying; the tool step runs it, and a further answer call writes the reply. A message routed to `fallback` gets a fixed reply with no model call. Message 809 runs three of the five steps: route, retrieve and answer. Its trace has four spans, a root named `message` and one child for each step.

The messages come from Amazon's MASSIVE dataset, version 1.1. Its English locale, en-US, is the source of this book's traffic. A row of the dataset is an utterance, and once an utterance is in the traffic it is a message. MASSIVE's data is licensed CC BY 4.0, and the dataset is described in [FitzGerald and colleagues, 2023](https://aclanthology.org/2023.acl-long.235/), published in the Proceedings of ACL 2023. MASSIVE has 52 locale files, one of them the English seed. That seed is SLURP, a spoken-language dataset whose English text crowd workers wrote from prompts, as [Bastianelli and colleagues, 2020](https://aclanthology.org/2020.emnlp-main.588/) describe. SLURP's text is also CC BY 4.0. Crowd workers wrote these texts for the datasets, in the voice of someone talking to an assistant. They are not logs from any real assistant. Ambrewick, its tools and its knowledge base are the book's own.

**Working rule:** Make one trace for each user message, with a root that covers the message's whole time and one span for each step its work went through. A trace that covers a run of several messages, or only some of the steps, cannot answer a question about one message, and a log line that lacks the trace ID cannot be joined to the others.

## Replay and the virtual clock {#replay-and-the-virtual-clock}

Message 809's trace needs a time for each step, and here those times come from a recording, not from a clock. A replay gives each model call the reply the recording holds, together with the call's recorded time and its [token counts](#three-token-counts). Nothing waits for a model here, and nothing is measured. The [OpenTelemetry Specification, Trace API](https://raw.githubusercontent.com/open-telemetry/opentelemetry-specification/v1.52.0/specification/trace/api.md), at v1.52.0, expects a span's timestamps to reflect the elapsed real time of the operation, so the book's times are the recording's, replayed, by choice. The replay advances a virtual clock by the recorded time of each call. The clock is an integer count of nanoseconds since the Unix epoch, in UTC, and it starts at the message's arrival. Once the replay has run, the clock says how long the message took. The same recording moves the clock by the same amounts on every run.

The dev day is one day of twenty messages, and it is the only day this chapter uses. Each model call on it was recorded once, on the recording machine, a 4-vCPU Intel Xeon at 2.10 GHz, which ran Qwen3-4B-Instruct-2507 in its Q4_K_M GGUF file. The examples replay that recording: each model call gets the reply the run gave, with its recorded time and token counts, and no example runs a model. A hosted model answers in other times. The method below carries over to it, and the numbers do not.

A call's token counts are not a time, so they do not move the clock. They are attributes that the recording holds for each call, and the span carries them. [Cached input tokens](#three-token-counts) are derived, not reported: the prompt tokens minus the tokens llama.cpp evaluated, from its performance counters. Chapter 6 explains the derivation.

Replaying message 809 takes two model calls, and the replay prints each one and their total:

Example `replay-one-message` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Replay one dev-day message through the assistant, answering each model call from the recording, and print what each
call cost on the virtual clock. The printed times and token counts are the recording's; the point rests on the route
call and the answer call of this one message."""
from lib.dayrun import run_dev_day
from lib.report import fmt_int, fmt_ms

(run,) = run_dev_day(["809"])                          # a device request: route, retrieve, answer
outcome = run.outcome

print("message text:", run.message.text)
print("route chosen:", outcome.route)
print("reply source:", outcome.source)
print("steps:", ", ".join(step.step for step in outcome.steps))
calls = [step for step in outcome.steps if step.step in ("route", "answer")]   # retrieve takes no model time
for step in calls:
    print(f"{step.step} call, time:", fmt_ms(step.end_ns - step.start_ns))
    print(f"{step.step} call, input tokens:", fmt_int(step.prompt_tokens))
    print(f"{step.step} call, cached input tokens:", fmt_int(step.cached_tokens))
    print(f"{step.step} call, output tokens:", fmt_int(step.completion_tokens))
print("message, time in model calls:", fmt_ms(sum(s.end_ns - s.start_ns for s in calls)))
# The clock moved by exactly the steps' times, so the steps account for all of the message's time.
assert run.replied_ns - run.arrived_ns == sum(step.end_ns - step.start_ns for step in outcome.steps)
assert outcome.source == "model"
```

Output:

```text
message text: brew coffee at noon
route chosen: devices
reply source: model
steps: route, retrieve, answer
route call, time: 3,336.3 ms
route call, input tokens: 142
route call, cached input tokens: 6
route call, output tokens: 6
answer call, time: 8,184.4 ms
answer call, input tokens: 331
answer call, cached input tokens: 192
answer call, output tokens: 38
message, time in model calls: 11,520.7 ms
```

```
route call, time: 3,336.3 ms
route call, input tokens: 142
route call, cached input tokens: 6
route call, output tokens: 6
answer call, time: 8,184.4 ms
answer call, input tokens: 331
answer call, cached input tokens: 192
answer call, output tokens: 38
message, time in model calls: 11,520.7 ms
```

The route call takes 3,336.3 ms, and the answer call takes 8,184.4 ms. Together they make the 11,520.7 ms the message spent in model calls. The replay gives the retrieve step no time, because the recording holds none for the search. The recorded run spent 7.3 ms between the route call's end and the answer call's start, and the replay drops that gap. An assertion on the clock checks only the replay's code: the clock moves by step times alone, so it can't find a gap the recording dropped.

**Working rule:** Let the recording move the clock, and never add a step's time by hand. Put an assertion beside the clock that checks its movement against the steps, so that a step which drops its time fails its run and does not reach a reader as a short total.

## Spans by hand {#spans-by-hand}

With the replay's steps and times in hand ([Replay and the virtual clock](#replay-and-the-virtual-clock)), the SDK can make the spans. This chapter's code uses the OpenTelemetry SDK for Python at 1.45.2. The SDK's tracer makes the spans, and two parts it's configured with decide where they go. A span processor is called when each span starts and when it ends, and on end it hands the span to an exporter, which sends it somewhere: to memory, a file or an [OTLP](#otlp-over-http) endpoint. The code here uses `SimpleSpanProcessor`, which exports each span at the moment it ends. The batch processor, by contrast, exports later, in batches, on a timer, so code that prints before a flush may find none of the spans, and a full queue drops them ([OpenTelemetry Specification, Trace SDK](https://raw.githubusercontent.com/open-telemetry/opentelemetry-specification/v1.52.0/specification/trace/sdk.md), v1.52.0). We use the simple processor so that every span has been exported by the time it's printed. In production we recommend the batch processor, because the simple one calls the exporter on the thread that ends the span, so a slow exporter slows the request. The SDK's source for `SimpleSpanProcessor.on_end` at 1.45.2 makes that call directly. The exporter here is an in-memory one, which keeps the spans in a list inside the process.

The SDK takes a span's start time when the span is opened. Its `start_span` call has no argument for the end time, so the end goes to a separate call. The helper in `lib/tracing.py` does both, from the times it is given:

```python
recorded = tracer.start_span(name, context=context, kind=kind, start_time=start_ns, attributes=attributes)
recorded.end(end_time=end_ns)
```

Each time is an integer count of nanoseconds, and each comes from the virtual clock, which [the replay section](#replay-and-the-virtual-clock) explains. No code here reads the machine's own clock, so the same recording gives the same spans every time it runs.

Leaving the end time to the SDK would not fail. The span would end at the machine's clock when `end()` was called, and that clock runs at a different pace on each run. The same message would then print a different duration each time, and the duration would have nothing to do with the recording. The helper avoids that by taking the end time from the caller, and it refuses an end time that falls before the start, since that would print a negative duration.

A trace ID is the number every span of one trace carries, and a span ID is the number of one span. The SDK's default generator draws both at random, so `lib/ids.py` counts them instead, 1, 2, 3, and starts again for each run. A span's parent is the span whose work it is part of; its span context, chiefly the trace ID, span ID and trace flags, is what lets other code and other processes name it. The helper takes a parent span and puts it in context, so that a child span names its parent.

The resource describes what made the telemetry and is the same on every span one tracer provider makes: `service.name`, `service.version`, `service.instance.id`. For this book the service is `ambrewick-assistant`, at the version the recording was made with, and its instance ID is a fixed string set by hand, since the SDK's default is a new random UUID on every run.

An attribute is a key and a value recorded on a span or a resource, such as `gen_ai.request.model`. The attributes in this chapter are the book's own. Every step's span carries `ambrewick.step`, which names the step it came from. The root has no `ambrewick.step`; it carries `ambrewick.route` and `ambrewick.reply.source`, which is why the tree prints `(root)` for it. The two model calls also carry `ambrewick.tokens.input`, `ambrewick.tokens.cached` and `ambrewick.tokens.output`. The spans are named by step, `route`, `retrieve` and `answer`, and the root is named `message`. They keep the SDK's default [span kind](#span-kind-follows-the-process). These are rough names on purpose; chapter 2 replaces them.

Example `build-one-trace` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Build one dev-day message's trace by hand: a span per step, each with its explicit start and end times, from sequential
IDs, a synchronous processor and an in-memory exporter. The steps and their times come from the replay; the printed
lines rest on the span count and on every child span's parent."""
from lib.dayrun import RELEASE, run_dev_day
from lib.export import spans_to_rows
from lib.ids import SequentialIds
from lib.report import fmt_int
from lib.tracing import make_provider, span
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

(run,) = run_dev_day(["809"])
outcome = run.outcome

# The resource names the service; service.instance.id is set, not drawn at random. Spans export as they end.
exporter = InMemorySpanExporter()
provider = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", run.clock, SequentialIds(),
                         exporter, "https://opentelemetry.io/schemas/1.44.0")
tracer = provider.get_tracer("ambrewick.assistant")
# The root is the message. Its span is made first, and each step's span names it as parent.
root = span(tracer, "message", run.arrived_ns, run.replied_ns,
            attributes={"ambrewick.route": outcome.route, "ambrewick.reply.source": outcome.source})
for step in outcome.steps:
    name = f"tool {step.name}" if step.step == "tool" else step.step      # named by step, not by the standard
    attributes = {"ambrewick.step": step.step}
    if step.step in ("route", "answer"):                                  # model calls carry their token counts
        attributes |= {"ambrewick.tokens.input": step.prompt_tokens, "ambrewick.tokens.cached": step.cached_tokens,
                       "ambrewick.tokens.output": step.completion_tokens}
    span(tracer, name, step.start_ns, step.end_ns, parent=root, attributes=attributes)

rows = spans_to_rows(exporter)                 # sorted by (trace, start, span), so the order is fixed
root_row = next(row for row in rows if row["parent_span_id"] is None)
children = [row for row in rows if row["parent_span_id"] is not None]
assert len({row["trace_seq"] for row in rows}) == 1                       # one message, one trace
assert all(row["parent_span_id"] == root_row["span_id"] for row in children)
print("spans in the trace:", fmt_int(len(rows)))
print("spans under the root:", fmt_int(len(children)))
route = next(row for row in children if row["name"] == "route")
print("route span, input tokens on the span:", fmt_int(route["attributes"]["ambrewick.tokens.input"]))
```

Output:

```text
spans in the trace: 4
spans under the root: 3
route span, input tokens on the span: 142
```

Message 809's four spans come from those calls. Each child is made with the root as its parent, by one line:

```python
span(tracer, name, step.start_ns, step.end_ns, parent=root, attributes=attributes)
```

The script then verifies that all four spans share one trace ID, and that every child names the root as its parent. The output reports 4 spans in the trace, 3 of them under the root, and the [input tokens](#three-token-counts) on the route span, 142.

What goes wrong in production is quieter than a wrong number. A span is exported only when it ends, because the simple processor passes each span to the exporter as soon as the span finishes, as the specification's [SDK page](https://raw.githubusercontent.com/open-telemetry/opentelemetry-specification/v1.52.0/specification/trace/sdk.md) says, so a span whose work never reaches its `end()` call is never exported at all. In live code the root covers the whole message, so it ends last, and a process that crashes partway through a message loses the root and the step that was running. The trace then arrives as finished steps whose parent never arrives, and with the batch processor, the spans still in its queue are lost too. The examples end the root first only because they build the spans after the replay, which live code never does. The check that finds the one span with no parent is what catches such a trace.

**Working rule:** In a replay, end every span with an explicit end time from the replay's clock. In live code, let the SDK take both times from the machine's clock. Either way, check each trace for its root, exactly one span with no parent, because a trace without one is what a crash leaves, and it reads as a few short steps, not as a failure.

## The tree of one trace {#the-tree-of-one-trace}

The four spans that [Spans by hand](#spans-by-hand) made for message 809 form a tree by their parent links, and the script then checks how their times add up. The tree lists the root and its three steps, and the lines after it give their times and checks:

Example `print-trace-tree` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Print one dev-day message's trace as a tree, with each span's step, then check how its times add up. The spans are the
ones build-one-trace makes. The steps run one after another, so none overlap and the message's time is their sum. Where
spans do overlap, a parent's duration is not the sum of its children's; this trace shows no overlap."""
from lib.dayrun import RELEASE, run_dev_day
from lib.export import spans_to_rows
from lib.ids import SequentialIds
from lib.report import fmt_ms
from lib.tracing import make_provider, span
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

(run,) = run_dev_day(["809"])
outcome = run.outcome

exporter = InMemorySpanExporter()
provider = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", run.clock, SequentialIds(),
                         exporter, "https://opentelemetry.io/schemas/1.44.0")
tracer = provider.get_tracer("ambrewick.assistant")
root = span(tracer, "message", run.arrived_ns, run.replied_ns,
            attributes={"ambrewick.route": outcome.route, "ambrewick.reply.source": outcome.source})
for step in outcome.steps:
    name = f"tool {step.name}" if step.step == "tool" else step.step
    span(tracer, name, step.start_ns, step.end_ns, parent=root, attributes={"ambrewick.step": step.step})

rows = spans_to_rows(exporter)
root_row = next(row for row in rows if row["parent_span_id"] is None)
children = [row for row in rows if row["parent_span_id"] is not None]


def print_tree(row, depth):
    """Print a span, then its children one level further in. Shows the shape of the trace, not its times."""
    print("  " * depth + f"{row['name']}  step: {row['attributes'].get('ambrewick.step', '(root)')}")
    for child in (r for r in rows if r["parent_span_id"] == row["span_id"]):
        print_tree(child, depth + 1)


print_tree(root_row, 0)
# Sorted by start, two steps overlap exactly when a step starts before the one before it has ended.
ordered = sorted(children, key=lambda row: row["start_ns"])
overlap = any(later["start_ns"] < earlier["end_ns"] for earlier, later in zip(ordered, ordered[1:]))
root_time = root_row["end_ns"] - root_row["start_ns"]
steps_time = sum(row["end_ns"] - row["start_ns"] for row in children)
print("message span, time:", fmt_ms(root_time))
print("steps, time added up:", fmt_ms(steps_time))
print("steps overlap in time:", "yes" if overlap else "no")
print("message time equals the sum of its steps:", "yes" if root_time == steps_time else "no")
assert not overlap and root_time == steps_time
```

Output:

```text
message  step: (root)
  route  step: route
  retrieve  step: retrieve
  answer  step: answer
message span, time: 11,520.7 ms
steps, time added up: 11,520.7 ms
steps overlap in time: no
message time equals the sum of its steps: yes
```

```
message  step: (root)
  route  step: route
  retrieve  step: retrieve
  answer  step: answer
message span, time: 11,520.7 ms
steps, time added up: 11,520.7 ms
steps overlap in time: no
message time equals the sum of its steps: yes
```

Indentation carries the parent links, so the three steps of message 809 sit one level under the root. The [OpenTelemetry Specification](https://raw.githubusercontent.com/open-telemetry/opentelemetry-specification/v1.52.0/specification/overview.md) calls a trace a directed acyclic graph of spans, and the parent links make that graph a tree, one parent for each span. The tree gives no times, so the times come from the next lines.

A child span may end after its parent. The specification's overview draws one that does, and it sets no rule against that ([OpenTelemetry Specification, Overview: Traces, Spans, SpanContext](https://raw.githubusercontent.com/open-telemetry/opentelemetry-specification/v1.52.0/specification/overview.md), tag v1.52.0). So a parent's duration is not the sum of its children's when they overlap, and it can differ from their sum when they leave gaps. In the replay, message 809's steps neither overlap nor leave a gap: the answer starts when the route ends. The script tests that, and the output gives the message's time as 11,520.7 ms and its steps' time as 11,520.7 ms, which are the same number.

A reader is tempted to read a parent's bar as the work its children did. A bar shows only where the parent started and stopped, and a gap is work no child records. Neither case is in this replay.

Figure 1.1 draws the same trace as a waterfall. The waterfall, one bar per span on a time axis, is the view tracing tools draw, and the [specification's overview](https://raw.githubusercontent.com/open-telemetry/opentelemetry-specification/v1.52.0/specification/overview.md) sketches it; the specification doesn't define it as a format, and this figure is the book's own drawing of it. It has one bar for each span, from the span's start to its end, in seconds after the message arrives. On top is the whole message's bar, then the route's bar from arrival, the retrieve step as a tick where the route ends, and the longer answer bar from there to the message's end.

*Figure 1.1. The spans of message 809, in seconds after it arrives.*

![The answer bar of message 809 starts where the route bar ends and is the longer of the two, and the retrieve step is a tick with no width](https://rollingedition.ai/books/observability-for-llm-applications/2026.11.2/figures/dev-day-waterfall.svg)

Example `figure-dev-day-waterfall` (Python 3.13.16 · bm25s 0.3.16 · matplotlib 3.11.2 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Draw one dev-day message's trace as a waterfall: each span a bar from its start to its end, after the message arrives.
The bars are the spans of build-one-trace, from the replay's recorded times, so the figure shows the order and length of
the steps. The printed lines are the values the figure's text quotes."""
from lib.dayrun import run_dev_day
from lib.figures import ACCENT, INK, MUTED, new_figure, save
from lib.report import fmt_ms

(run,) = run_dev_day(["809"])
outcome, arrived = run.outcome, run.arrived_ns

# One bar per span: the message first, then its steps in order. The answer is the accent; the route is ink.
bars = [("message", arrived, run.replied_ns, MUTED)]
bars += [(s.step, s.start_ns, s.end_ns, ACCENT if s.step == "answer" else INK) for s in outcome.steps]
fig, ax = new_figure(height=2.4)
for row, (label, start, end, colour) in enumerate(bars):
    left, width = (start - arrived) / 1e9, (end - start) / 1e9             # seconds after arrival
    if width > 0:
        ax.barh(row, width, left=left, height=0.6, color=colour)
    else:                                                                  # a step with no time is a tick, not a bar
        ax.plot([left], [row], marker="|", markersize=10, color=colour)
ax.set_yticks(range(len(bars)), [label for label, _, _, _ in bars])
ax.invert_yaxis()
ax.set_xlabel("seconds after the message arrives")
save(fig, "dev-day-waterfall")

steps = {s.step: s for s in outcome.steps}                                 # one span per step in this message
route, answer = steps["route"], steps["answer"]
print("message, time from arrival to reply:", fmt_ms(run.replied_ns - arrived))
print("route span, time:", fmt_ms(route.end_ns - route.start_ns))
print("retrieve span, time:", fmt_ms(steps["retrieve"].end_ns - steps["retrieve"].start_ns))
print("answer span, time:", fmt_ms(answer.end_ns - answer.start_ns))
print("answer span starts, after arrival:", fmt_ms(answer.start_ns - arrived))
# The steps run one after another: the answer starts exactly when the route ends, so the bars do not overlap.
assert answer.start_ns == route.end_ns
```

Output:

```text
figure: figures/dev-day-waterfall.svg
message, time from arrival to reply: 11,520.7 ms
route span, time: 3,336.3 ms
retrieve span, time: 0.0 ms
answer span, time: 8,184.4 ms
answer span starts, after arrival: 3,336.3 ms
```

The answer span starts 3,336.3 ms after arrival, which is when the route ends. The figure's order is the order the steps ran, and its lengths are the times the clock recorded.

**Working rule:** Print a trace as a tree of parent links, and check that its children neither overlap nor leave gaps before you add their times. When they do, report the parent's time and the children's separately.

## Where the time went in twenty messages {#where-the-time-went-in-twenty-messages}

Message 809 is one trace, and the dev day is twenty of them. [One message, one trace](#one-message-one-trace) keeps each message's steps together, so the day's steps can be added up. A fallback reply is the fixed text Ambrewick sends when the router chooses `fallback`; no model writes it, and its span says so. On the dev day, 6 of 20 messages got one. A fallback reply is the right answer only for a message that no tool or article can resolve.

Example `sum-dev-day-steps` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Replay all 20 dev-day messages and add up each model step over the day: its calls, its recorded time, its tokens, and its
share of the day's model time and tokens. Tool time is not in the recording (the tools are modelled), so it is counted
and left out of the shares; retrieve and fallback take no time. The route-to-answer gap is the recorder's, not the replay's."""
from collections import Counter
from lib.dayrun import recorded_gap_ns, run_dev_day
from lib.report import fmt_int, fmt_ms, fmt_share

MODEL_STEPS = ("route", "answer")
runs = run_dev_day()                                   # all 20 messages, in arrival order
calls, time_ns, tokens = Counter(), Counter(), Counter()
cached, overlapping, fallbacks = Counter(), 0, 0
for run in runs:
    ordered = sorted(run.outcome.steps, key=lambda s: s.start_ns)
    overlapping += any(later.start_ns < earlier.end_ns for earlier, later in zip(ordered, ordered[1:]))
    fallbacks += run.outcome.source == "fallback"
    for step in run.outcome.steps:
        calls[step.step] += 1
        if step.step in MODEL_STEPS:       # the recording's times and tokens; input counts cached tokens too
            time_ns[step.step] += step.end_ns - step.start_ns
            tokens[step.step] += step.prompt_tokens + step.completion_tokens
            cached[step.step] += step.cached_tokens
            tokens[f"{step.step} input"] += step.prompt_tokens

slowest = max(runs, key=lambda run: run.replied_ns - run.arrived_ns)     # the first of the slowest, if two tie
total_time, total_tokens = sum(time_ns[s] for s in MODEL_STEPS), sum(tokens[s] for s in MODEL_STEPS)
input_total = sum(tokens[f"{s} input"] for s in MODEL_STEPS)
print("messages in the dev day:", fmt_int(len(runs)))
print("messages whose steps overlap in time:", f"{overlapping} of {len(runs)}")
print("messages answered by the fallback reply:", f"{fallbacks} of {len(runs)}")
print("slowest message:", slowest.message.message_id)
print("slowest message time:", fmt_ms(slowest.replied_ns - slowest.arrived_ns))
print("slowest message route:", slowest.outcome.route)
for step in MODEL_STEPS:
    print(f"{step} calls:", fmt_int(calls[step]))
    print(f"{step}, recorded time:", fmt_ms(time_ns[step]))
    print(f"{step}, share of model time:", fmt_share(time_ns[step], total_time))
    print(f"{step}, share of tokens (input plus output):", fmt_share(tokens[step], total_tokens))
print("tool calls:", fmt_int(calls["tool"]))
print("retrieve calls:", fmt_int(calls["retrieve"]))
print("route to answer gap, message 809:", fmt_ms(recorded_gap_ns("809", "route", "answer")))
print("input tokens, total:", fmt_int(input_total))
print("cached input tokens, total:", fmt_int(sum(cached[s] for s in MODEL_STEPS)))
print("output tokens, total:", fmt_int(total_tokens - input_total))
assert calls["route"] == len(runs)               # every message is routed once
assert overlapping == 0                          # the steps never overlap in the replay
```

Output:

```text
messages in the dev day: 20
messages whose steps overlap in time: 0 of 20
messages answered by the fallback reply: 6 of 20
slowest message: 3271
slowest message time: 36,230.7 ms
slowest message route: alarms
route calls: 20
route, recorded time: 35,500.6 ms
route, share of model time: 16.7%
route, share of tokens (input plus output): 21.2%
answer calls: 17
answer, recorded time: 176,519.9 ms
answer, share of model time: 83.3%
answer, share of tokens (input plus output): 78.8%
tool calls: 3
retrieve calls: 8
route to answer gap, message 809: 7.3 ms
input tokens, total: 13,417
cached input tokens, total: 8,299
output tokens, total: 775
```

The script replays all twenty messages, one after another, and adds up each model step over the day. The day's tool calls went to the in-process tools, the calendar, alarm and list tools, whose durations are modelled from a table in the book's configuration, not recorded, so the shares leave them out and count them only as calls. Retrieve takes no recorded time either. The script also counts the messages whose steps overlap in time, and the count is 0 of 20. So the day's sums are sums of step times, and they are not splits of each message's root time.

The answer step holds most of the day's model time, 83.3%, while the route step holds 21.2% of the tokens against 16.7% of the time. Answer calls outnumber the messages a model answered, because each message that called a tool needed a further answer call after the tool returned, so the answer step ran 17 times. The shares are over the day's model time and its tokens, input plus output, and the output prints both totals.

Figure 1.2 draws the two shares for each model step. Time and tokens do not share a shape, as the figure shows.

*Figure 1.2. Each model call's share of the dev day's model time and of its tokens, over 20 messages.*

![The answer call holds most of the model time, while the route call holds a bigger share of the tokens than of the time](https://rollingedition.ai/books/observability-for-llm-applications/2026.11.2/figures/dev-day-step-shares.svg)

Example `figure-dev-day-step-shares` (Python 3.13.16 · bm25s 0.3.16 · matplotlib 3.11.2 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Draw each model step's share of the dev day's model time, beside its share of the tokens (input plus output), over all
20 messages. Each bar is labelled with the share the example prints, so the figure and the printed lines are one set of
numbers. Tool time is not in the recording, so the tool step is not drawn."""
from collections import Counter
from lib.dayrun import run_dev_day
from lib.figures import ACCENT, INK, new_figure, save
from lib.report import fmt_int, fmt_ms, fmt_share

MODEL_STEPS = ("route", "answer")
runs = run_dev_day()
calls, time_ns, tokens = Counter(), Counter(), Counter()
for run in runs:
    for step in (s for s in run.outcome.steps if s.step in MODEL_STEPS):
        calls[step.step] += 1
        time_ns[step.step] += step.end_ns - step.start_ns
        tokens[step.step] += step.prompt_tokens + step.completion_tokens      # input plus output

total_time, total_tokens = sum(time_ns.values()), sum(tokens.values())
time_labels = [fmt_share(time_ns[s], total_time) for s in MODEL_STEPS]
token_labels = [fmt_share(tokens[s], total_tokens) for s in MODEL_STEPS]
fig, ax = new_figure(height=2.6)
positions = list(range(len(MODEL_STEPS)))
time_bars = ax.bar([p - 0.2 for p in positions], [100 * time_ns[s] / total_time for s in MODEL_STEPS], width=0.4,
                   color=ACCENT, label="share of model time")
token_bars = ax.bar([p + 0.2 for p in positions], [100 * tokens[s] / total_tokens for s in MODEL_STEPS], width=0.4,
                    color=INK, label="share of tokens")
ax.bar_label(time_bars, labels=time_labels, padding=2)
ax.bar_label(token_bars, labels=token_labels, padding=2)
ax.set_xticks(positions, list(MODEL_STEPS))
ax.set_ylim(0, 100)
ax.set_ylabel("percent of the dev day")
ax.legend(loc="upper left")          # the route bars reach only about 21 percent, so the top left is clear of labels
save(fig, "dev-day-step-shares")

print("messages in the dev day:", fmt_int(len(runs)))
for step, time_label, token_label in zip(MODEL_STEPS, time_labels, token_labels):
    print(f"{step} calls:", fmt_int(calls[step]))
    print(f"{step}, recorded time:", fmt_ms(time_ns[step]))
    print(f"{step}, share of model time:", time_label)
    print(f"{step}, tokens, input plus output:", fmt_int(tokens[step]))
    print(f"{step}, share of tokens:", token_label)
print("model time, total:", fmt_ms(total_time))
print("tokens, input plus output, total:", fmt_int(total_tokens))
assert sum(calls.values()) == 37     # 20 route calls and 17 answer calls, as the recording holds
```

Output:

```text
figure: figures/dev-day-step-shares.svg
messages in the dev day: 20
route calls: 20
route, recorded time: 35,500.6 ms
route, share of model time: 16.7%
route, tokens, input plus output: 3,003
route, share of tokens: 21.2%
answer calls: 17
answer, recorded time: 176,519.9 ms
answer, share of model time: 83.3%
answer, tokens, input plus output: 11,189
answer, share of tokens: 78.8%
model time, total: 212,020.5 ms
tokens, input plus output, total: 14,192
```

A step's share of time says where the day's waiting went, and its share of tokens says where the day's input and output came from. The two are different questions, and this chapter answers both; which step costs the most money is chapter 6's question, and it needs the prices as well as the tokens.

**Working rule:** Sum each step's recorded time and tokens over the messages, and print each share beside its denominator. Name any step whose time is not recorded and leave it out of the shares, so that a reader can see which part of the day the sums do not cover.

## What this version does not do yet {#whats-rough}

This version is a rough one, and each part of it has a later chapter that makes it solid. In order:

- **The names.** The spans are named by the book's own steps. Chapter 2 names each span by the standard's names, sets its kind, and checks it with a validator, which every span here fails.
- **The model calls.** The spans are made by hand. Chapter 3 shows what the official instrumentation of the `openai` client library emits for the same kind of call.
- **The second process.** The trace is one process's record. Chapter 4 joins the spans of the contacts team's server, which runs as a separate process, to this trace.
- **The storage.** The spans live in memory and disappear when the process ends. Chapter 5 sends them to a [backend](#otlp-over-http) that stores them.
- **[The tail](#tail-percentiles-with-intervals).** Twenty messages cannot give a tail [percentile](#tail-percentiles-with-intervals) with any confidence. Chapter 7 gives percentiles with their counts and an [interval](#tail-percentiles-with-intervals).
- **The sampling.** Every trace is kept. Chapter 11 decides which traces to keep, and why.
- **The prompts.** The spans hold no prompt text, on purpose. Chapter 3 names the switch that would record it, and chapter 12 covers what that switch leaks.
- **The wrong routes.** 6 of 20 dev-day messages got the fallback reply, and this chapter does not check whether each route was right. Chapter 8 does.

## The decisions this chapter made {#trace-a-request-decisions}

These decisions shape the rest of the book:

- The spans are named by step for now. From chapter 2 on, the book uses the standard's names.
- Each duration is a recorded value and never a live measurement, so every printed time can be run again and matched.
- The spans are exported at the moment they end, by a synchronous processor, so that every span has been exported by the time it is printed.
- A share is printed with its denominator, and a step whose time is not recorded is left out of the shares rather than estimated.
- Each trace is one message's, and the sums over the day add up the messages' steps as the recording holds them, with no other measure built from the spans.

**Working rule:** Answer a question about one message from that message's trace alone. Every span of the message shares the trace ID, and the root covers its whole time, so the trace holds that message's steps and no other message's. A span or log line without the ID cannot be placed in the answer, so leave it out and say so, rather than guess which message it belongs to. A guess would put one message's time into another message's total.

# Name spans the way the standard does

By the end of this chapter you can give each span in the assistant's traces the name, the kind and the attributes that OpenTelemetry's GenAI conventions expect for its step. You can say which software made the span and which schema version its names follow, and you can run a check that fails when a span drifts from the registry.

Ambrewick's on-call engineers, who run the assistant whose traces this book builds ([one message, one trace](#one-message-one-trace)), want those traces in the tools they already run. Those tools know one vocabulary: the names the conventions give a model call, a retrieval, a tool run and an agent's turn. [Chapter 1's names](#spans-by-hand) mean nothing there. The validator, the check this chapter builds, compares each span with the registry's rules. Run on message 809, a devices question with a retrieval, its 4 spans draw 4 findings, one per span, and each says the span has no known span type. The SDK raised none of them, because the SDK accepts any name. So this chapter gives each span the standard's name and kind, records who made it, and builds the check that keeps the names right. Chapter 3 then measures a client library's spans against these names.

## The standard at a Development version {#the-standard-at-v0-1-0}

A [backend](#otlp-over-http) answers a question about a span by its name. A question such as how long the model calls took this week only has one answer if every backend agrees which spans are model calls, and the standard is that agreement. A semantic convention is a published name, type and meaning for a span, attribute or [metric](#totals-from-metrics-not-spans), so that any backend reads the same name the same way. The standard is OpenTelemetry's GenAI semantic conventions.

The GenAI names first lived in OpenTelemetry's core semantic conventions repository. That repository deprecated its names under the `gen_ai` prefix in its release 1.42.0, and they moved to a repository of their own ([changelog](https://raw.githubusercontent.com/open-telemetry/semantic-conventions/v1.42.0/CHANGELOG.md)). This book follows that repository's first standalone release, GenAI conventions, version 0.1.0 ([changelog](https://raw.githubusercontent.com/open-telemetry/semantic-conventions-genai/v0.1.0/CHANGELOG.md)).

The conventions come in two forms: pages for people to read, and the registry, a YAML model of the span types, their kinds and their attributes that a program can read. The book's validator reads the registry at the pinned version, so the names it checks are the ones the registry lists.

Every page of the GenAI conventions, version 0.1.0, is Development: its names may change in any release. The specification defines Development for its own components, and its status page says of such a component: "The component MAY be removed without prior notice. The component SHOULD NOT be used in production." ([status page](https://raw.githubusercontent.com/open-telemetry/opentelemetry-specification/v1.52.0/specification/document-status.md)). The GenAI pages carry the same status, and their changelog shows the names moving. The first standalone release renamed the [inference span](#span-types-for-each-step) type from `gen_ai.inference.client` to `gen_ai.client.inference`. The book's names follow that release, so a later release can rename them.

**Working rule:** Pin the conventions' version beside every name you publish. A dashboard built on a Development name needs a check that runs when the name changes.

## Span types for each step {#span-types-for-each-step}

The registry sorts spans into span types, and each type has a name pattern, a [span kind](#span-kind-follows-the-process) and the attributes it requires. [Chapter 1's steps](#spans-by-hand) fall into four of them. An inference span is the span of one client call to a generative model that answers the prompt or asks for a tool call. A retrieval span is the span of one run of the application's retrieval step, which returns the documents relevant to a query. A tool-execution span is the span of one run of a tool, named for the tool. An agent-invocation span is the span of one invocation of an agent. The book's agent runs in the assistant's process, so its span is the in-process type, which also covers workflows. A remote agent's span is a CLIENT span of its own type. The route and answer steps are model calls, the retrieve step is a search, the tool runs are tool runs, and each message's root is one agent run.

| Span type | Name pattern | Kind | Operation name |
| --- | --- | --- | --- |
| Inference | `{operation} {model}` | CLIENT, or INTERNAL in process | `chat` |
| Retrieval | `{operation}` | INTERNAL | `retrieval` |
| Tool execution | `execute_tool {tool}` | INTERNAL | `execute_tool` |
| Agent invocation | `invoke_agent {agent}` | INTERNAL in process; CLIENT for a remote agent | `invoke_agent` |

Example `inference-span-names` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Print the span name each step gets from the assistant, beside the registry's pattern for that span type. The names are
the spans', the patterns are the registry's, and each assert checks one span's name against its pattern.

The point rests on the four name lines: the inference, tool and agent names from message 11159 (a route, an answer, a
tool call and a second answer), and the retrieval name from message 809."""
from lib.assistant import Assistant
from lib.bm25 import Retriever
from lib.case import load_articles, load_messages, load_tool_durations
from lib.clock import VirtualClock
from lib.dayrun import DAY, RECORDING, RELEASE
from lib.export import spans_to_rows
from lib.genai import REGISTRY_VERSION, SCHEMA_URL, SPAN_OPERATIONS, SPAN_TYPES
from lib.ids import SequentialIds
from lib.replay import Replay, ReplayContacts
from lib.tools import Tools
from lib.tracing import make_provider
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

replay = Replay(RECORDING)
retriever, tools = Retriever(load_articles(), RELEASE.top_k), Tools(load_tool_durations(), ReplayContacts(replay))
rows = {}
for message in (m for m in load_messages(DAY) if m.message_id in ("809", "11159")):
    clock, exporter = VirtualClock(DAY, start_ns=message.arrival_ns), InMemorySpanExporter()  # one exporter per message
    tracer = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", clock, SequentialIds(),
                           exporter, SCHEMA_URL).get_tracer("ambrewick.assistant", schema_url=SCHEMA_URL)
    Assistant(replay, retriever, tools, clock, tracer, RELEASE).handle(message)
    rows[message.message_id] = spans_to_rows(exporter)
agent = next(row for row in rows["11159"] if row["parent_span_id"] is None)  # the root is the agent's invocation
inference = next(row for row in rows["11159"] if row["attributes"].get("gen_ai.operation.name") == "chat")
tool = next(row for row in rows["11159"] if row["attributes"].get("gen_ai.operation.name") == "execute_tool")
retrieval = next(row for row in rows["809"] if row["attributes"].get("gen_ai.operation.name") == "retrieval")
print("GenAI conventions version:", REGISTRY_VERSION)
print("inference span name:", inference["name"])
print("retrieval span name:", retrieval["name"])
print("tool span name:", tool["name"])
print("agent span name:", agent["name"])
print("inference provider name:", inference["attributes"]["gen_ai.provider.name"])
print("inference prompt name:", inference["attributes"]["gen_ai.prompt.name"])
print("inference prompt version:", inference["attributes"]["gen_ai.prompt.version"])
# Model spans are `{operation} {model}`, retrieval is its operation alone, tools are `execute_tool {tool}`, the agent is
# `invoke_agent {agent}`. Each assert checks one span against its pattern.
assert inference["name"] == f"chat {RELEASE.model}" and retrieval["name"] == "retrieval"
assert tool["name"] == f"execute_tool {tool['attributes']['gen_ai.tool.name']}"
assert agent["name"] == f"invoke_agent {agent['attributes']['gen_ai.agent.name']}"
for span_type in sorted(SPAN_OPERATIONS):  # the operation names the registry defines, per span type
    print(f"operation names, {span_type}:", ", ".join(SPAN_OPERATIONS[span_type]))
for span_type in sorted(SPAN_TYPES):  # the attributes the validator requires, per span type
    print(f"required attributes, {span_type}:", len(SPAN_TYPES[span_type]["required"]))
```

Output:

```text
GenAI conventions version: 0.1.0
inference span name: chat qwen3-4b-instruct-2507
retrieval span name: retrieval
tool span name: execute_tool remove_item
agent span name: invoke_agent ambrewick-assistant
inference provider name: openai
inference prompt name: ambrewick.route
inference prompt version: p1
operation names, gen_ai.client.inference: chat, generate_content, realtime_inference, text_completion
operation names, gen_ai.execute_tool: execute_tool
operation names, gen_ai.invoke_agent.internal: invoke_agent
operation names, gen_ai.retrieval: retrieval
required attributes, gen_ai.client.inference: 2
required attributes, gen_ai.execute_tool: 2
required attributes, gen_ai.invoke_agent.internal: 1
required attributes, gen_ai.retrieval: 1
required attributes, mcp.client: 1
required attributes, mcp.server: 1
```

The model span changes most. Its name is the operation, a space, and the model's name, so a reader scanning a trace sees which model answered each call. Message 11159, a lists request with one tool call, has its first model call named `chat qwen3-4b-instruct-2507`. The registry gives one list of well-known values for `gen_ai.operation.name` on an inference span, and a custom value MAY be used beyond it ([registry attributes](https://raw.githubusercontent.com/open-telemetry/semantic-conventions-genai/v0.1.0/docs/registry/attributes/gen-ai.md)). The validator maps each value to a span type through a map the book makes, and that map gives the inference type `chat, generate_content, realtime_inference, text_completion`. The assistant writes `chat` for each of its calls. The example asserts the model span's name against the operation and the model the run used, and it builds the tool and agent names from the attributes their spans carry, so a drift in either one fails the run.

The retrieval span is named by its operation alone, `retrieval`. The registry's pattern leaves no room for the index it searched, so the knowledge base's name stays out of the span name. A tool run is named for its tool, `execute_tool remove_item`, the run of the list tool that removed an item in message 11159. The root is named `invoke_agent ambrewick-assistant`, and it replaces chapter 1's `message` span. We keep `invoke_agent` rather than `invoke_workflow`, because the model chooses the route and whether to call a tool. The model drives the control flow through tool calls, which is the case the registry's agent type describes.

One attribute the registry leaves open is the provider. In the book, the inference span's `gen_ai.provider.name` is `openai`, and that value is our judgement. The registry's well-known values for the attribute include no value for llama.cpp, and a provider the list lacks may take a custom value ([registry](https://raw.githubusercontent.com/open-telemetry/semantic-conventions-genai/v0.1.0/model/gen-ai/registry.yaml)). The attribute's general note says it "SHOULD be set based on the instrumentation's best knowledge and may differ from the actual upstream provider" ([client inference](https://raw.githubusercontent.com/open-telemetry/semantic-conventions-genai/v0.1.0/docs/gen-ai/client-inference.md)). We record `openai` because Ambrewick's client speaks OpenAI's API to its endpoint, and the official package records `openai` for that call, as chapter 3 shows. A reader whose model is served another way should choose by the same rule and say so.

Of the spans the assistant makes, the fallback span is the only one the registry does not name. The book keeps it, the validator flags it, and the [validation section](#validating-against-the-registry) says why that flag is the right answer.

**Working rule:** Name each span from its registry pattern, not from the function that made it, and take the operation name from the registry's well-known values. Where the registry gives no value for something you run, use the value the client and its official instrumentation would write, and say that it's a judgement.

## The span kind follows the process {#span-kind-follows-the-process}

A span's kind says where its work ran: CLIENT for a call out of the process, SERVER for one received, INTERNAL for work inside (two more, PRODUCER and CONSUMER, mark work handed to a queue). The model call is the hard case. The registry says "It's RECOMMENDED to use `CLIENT` kind when the GenAI system being instrumented usually runs in a different process than its client or when the GenAI call happens over instrumented protocol such as HTTP" ([client inference](https://raw.githubusercontent.com/open-telemetry/semantic-conventions-genai/v0.1.0/docs/gen-ai/client-inference.md)). A model behind an endpoint is reached by a call that leaves the assistant's process, so its span is CLIENT. The registry also allows INTERNAL for a model running in the same process, which is why the kind is a judgement at all. The book applies the rule with a test a span can show: whether the call names a server. A call that names a server is CLIENT, and a call that names none can be INTERNAL.

Example `span-kinds-by-process` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Give one model call two kinds: CLIENT when the model sits behind an endpoint, as the trace shows it, and INTERNAL
when the same assistant runs the model in process. Then run the validator on both.

The point rests on the two model-call kind lines and on the zero findings: the registry allows INTERNAL for an
in-process model (it says MAY), and the validator accepts it when the call names no server. An endpoint span marked
INTERNAL is flagged, because it names one."""
from lib.dayrun import DAY, RECORDING, run_day_traced
from lib.genai import REGISTRY_VERSION, validate
from lib.replay import Replay


class InProcess:
    """The recorded model, run as if it shared the assistant's process: the same answers, and no endpoint."""

    in_process = True

    def __init__(self, replay):
        self._replay = replay

    def reply(self, request):
        return self._replay.reply(request)


rows = run_day_traced(DAY, ["809"], live=False).spans  # a devices message: a route and an answer call, behind an endpoint
local = run_day_traced(DAY, ["809"], backend=InProcess(Replay(RECORDING)), live=False).spans  # the same model in process
endpoint = next(row for row in rows if row["name"].startswith("chat "))
in_process = next(row for row in local if row["name"].startswith("chat "))
retrieval = next(row for row in rows if row["name"] == "retrieval")
root = next(row for row in rows if row["parent_span_id"] is None)
marked = dict(endpoint, kind="INTERNAL")  # the endpoint's span, wrongly marked as in process

print("GenAI conventions version:", REGISTRY_VERSION)
print("model call kind, behind an endpoint:", endpoint["kind"])
print("model call kind, in process:", in_process["kind"])
address, port = endpoint["attributes"]["server.address"], endpoint["attributes"]["server.port"]
print("server the endpoint span names:", f"{address}:{port}")
print("findings on the in-process span:", len(validate(in_process)))
print("findings on the endpoint span marked INTERNAL:", len(validate(marked)))
print("retrieval span kind:", retrieval["kind"])
print("agent span kind:", root["kind"])
assert validate(endpoint) == [] and validate(in_process) == []  # both kinds are the registry's
assert "server.address" not in in_process["attributes"]  # an in-process model names no server
assert len(validate(marked)) == 1 and "kind is INTERNAL" in validate(marked)[0]
assert validate(retrieval) == [] and validate(root) == []  # INTERNAL is the registry's kind for these two types
```

Output:

```text
GenAI conventions version: 0.1.0
model call kind, behind an endpoint: CLIENT
model call kind, in process: INTERNAL
server the endpoint span names: localhost:8000
findings on the in-process span: 0
findings on the endpoint span marked INTERNAL: 1
retrieval span kind: INTERNAL
agent span kind: INTERNAL
```

Running message 809's model calls both ways shows the rule at work. Message 809 is a devices question with a route and an answer call. Behind the endpoint the span's kind is `CLIENT`, and the same calls run in process give `INTERNAL`. The endpoint's span names a server, and the in-process span names none. The validator reports `0` findings on the in-process span, which the example asserts. Marked INTERNAL, the endpoint's span still names a server, and the validator reports `1` finding on it. The finding's text is asserted to name the kind, `kind is INTERNAL`, and only its count is printed. That finding is the failure the rule prevents.

The [dev-day](#replay-and-the-virtual-clock) traces in this book are all CLIENT, because the recorded model calls were served over an endpoint. The in-process case is the same model called from the assistant's own code, and the book runs it only in this example. A reader who moves a model into the process should expect the kind to change with it, and should expect the validator to say so if the span still names a server.

The retrieval span and the agent span are both INTERNAL, which the example asserts for each, because their work runs inside the assistant. The printed kinds are `INTERNAL` for the retrieval span and `INTERNAL` for the agent span. The registry gives both kinds ([registry](https://raw.githubusercontent.com/open-telemetry/semantic-conventions-genai/v0.1.0/model/gen-ai/spans.yaml)), and the validator checks them.

**Working rule:** Give a model span CLIENT when the call goes to a server, even one on the same machine. Give it INTERNAL only when the model runs in your process and the span names no server, and let the validator check each kind you set.

## Which attributes a span must carry {#requirement-levels}

A name tells a backend what a span is. The requirement level tells it which attributes that span must carry. A requirement level says when an attribute must appear: required, conditionally required, recommended or opt-in ([requirement levels](https://raw.githubusercontent.com/open-telemetry/semantic-conventions/v1.45.0/docs/general/attribute-requirement-level.md)). A required attribute appears on every span of its type. A conditionally required one appears when its condition holds, and the registry writes the condition beside it. A recommended attribute says what a good span carries, and an opt-in one appears only when something switches it on.

The registry also says which attributes each span type must carry. The book's module, `lib.genai`, holds every requirement level from the registry, so the requirement levels and kinds that the [validator](#validating-against-the-registry) checks are the registry's, not a list someone typed. The validator checks the kind and the required attributes, and nothing else, so a span can pass it and still lack what the registry asks for in a conditional case. The validator's counts, as the inference-span-names example prints them, show how many each span type requires: `2` on an inference span, `2` on a tool-execution span, `1` on the retrieval span and `1` on the agent span. Its required attributes are its operation name and its provider name, so the [provider judgement](#span-types-for-each-step) is not optional. A span without either one fails the check.

Opt-in attributes are the ones to watch for privacy. The message contents of a model call are opt-in, so the book's spans carry none of them unless a switch asks for them, and chapter 3 says what that switch does.

Conditional requirements are the ones the validator does not read. `gen_ai.prompt.version` is conditionally required on the inference span when the span carries `gen_ai.prompt.name` and a version is available. `gen_ai.prompt.name` is conditionally required when a named prompt template is used ([registry](https://raw.githubusercontent.com/open-telemetry/semantic-conventions-genai/v0.1.0/model/gen-ai/spans.yaml)). The assistant's prompts are named and versioned, so its inference spans carry both: `ambrewick.route` and `p1` on the route call in message 11159. Chapter 10 queries that pair to tell releases apart. The validator reads only required attributes, so it would not report a span that lacks either one, and a gap in a conditional attribute is a gap it will not report.

**Working rule:** Read a span's requirement levels before you read its name. A missing required attribute is a defect in the span. A missing conditionally required attribute is a defect only when its condition holds, so read the condition in the registry before you file it.

## Who made the span {#who-made-the-span}

A span says what it measured, and two other places say who measured it: the [resource](#spans-by-hand) and the instrumentation scope. The instrumentation scope names the unit of code that made a span, usually an [instrumentation library](#a-call-through-the-client), and here the assistant's own module. A schema URL names a published telemetry schema, a release of the semantic conventions, that the telemetry follows. The prose never types a schema URL; each one here is printed by its example.

The resource carries three attributes the book sets itself. `service.name` is `ambrewick-assistant`. `service.version` is `1.0.0`, and it marks the release, which chapter 10 reads to split traces by release. `service.instance.id` is `dev-day-replay`. The [replay](#replay-and-the-virtual-clock) sets the instance ID itself, so a rerun names the same instance and its traces can be compared run to run. A process that restarts keeps its instance ID only if one was set, and a query that follows one instance through a restart needs the ID to stay put.

Example `resource-and-schema` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Print the resource and the instrumentation scope of the renamed spans, with the schema URL each one carries, beside
chapter 1's stamp.

The point rests on the schema lines: chapter 1's resource said 1.44.0, the renamed spans say 1.45.0, and the SDK's
constants have no 1.45.0 schema, which the assert checks. The book takes that URL from the registry's manifest
(genai.SCHEMA_URL), and make_provider puts it on the tracer as well as the resource."""
from lib.dayrun import RELEASE
from lib.genai import SCHEMA_URL
from lib.ids import SequentialIds
from lib.tracing import make_provider, span
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.semconv.schemas import Schemas

CHAPTER_1_SCHEMA = "https://opentelemetry.io/schemas/1.44.0"


def version_key(url):
    """Sort key for a schema URL: its version as numbers, so 1.9 sorts before 1.44."""
    return tuple(int(part) for part in url.rsplit("/", 1)[1].split("."))


exporter = InMemorySpanExporter()
provider = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", None, SequentialIds(),
                         exporter)
tracer = provider.get_tracer("ambrewick.assistant")  # no schema given: the tracer carries the provider's
span(tracer, "resource probe", 1, 2)  # one ended span, so the scope's schema can be read from it
scope = exporter.get_finished_spans()[0].instrumentation_scope
chapter_1 = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", None, SequentialIds(),
                          InMemorySpanExporter(), CHAPTER_1_SCHEMA)  # the resource chapter 1 built, read back from it
known = {schema.value for schema in Schemas}  # what opentelemetry-semantic-conventions 0.66b2 can stamp
print("chapter 1's resource schema URL:", chapter_1.resource.schema_url)
print("renamed spans' resource schema URL:", provider.resource.schema_url)
print("renamed spans' scope schema URL:", scope.schema_url)
print("instrumentation scope name:", scope.name)
print("highest schema in the SDK's constants:", max(known, key=version_key))
print("service.name:", provider.resource.attributes["service.name"])
print("service.version:", provider.resource.attributes["service.version"])
print("service.instance.id:", provider.resource.attributes["service.instance.id"])
assert SCHEMA_URL not in known  # the constants stop at 1.44.0, so the book takes its 1.45.0 from the registry
assert provider.resource.schema_url == scope.schema_url == SCHEMA_URL
assert provider.resource.attributes["service.instance.id"] == "dev-day-replay"  # set, not drawn at random
```

Output:

```text
chapter 1's resource schema URL: https://opentelemetry.io/schemas/1.44.0
renamed spans' resource schema URL: https://opentelemetry.io/schemas/1.45.0
renamed spans' scope schema URL: https://opentelemetry.io/schemas/1.45.0
instrumentation scope name: ambrewick.assistant
highest schema in the SDK's constants: https://opentelemetry.io/schemas/1.44.0
service.name: ambrewick-assistant
service.version: 1.0.0
service.instance.id: dev-day-replay
```

The schema URL moved in this chapter, and the example prints both values. [Chapter 1's resource](#spans-by-hand) said `https://opentelemetry.io/schemas/1.44.0`. That was the newest schema the pinned semantic-conventions package carries, `0.66b2`, and its highest schema is `https://opentelemetry.io/schemas/1.44.0`. Chapter 1's names followed no convention, so that stamp described nothing the book's spans said. The renamed spans stamp `https://opentelemetry.io/schemas/1.45.0`, which is the core semantic-conventions release that GenAI conventions v0.1.0 depend on. The GenAI conventions publish no schema URL of their own at v0.1.0. Core deprecated its `gen_ai.*` names in 1.42.0, when they moved to their own repository. So the stamp says which core release the resource's `service.*` names follow, and the GenAI version travels beside the check, `0.1.0`. The book's generated module takes that URL from the registry's manifest, and the example asserts that the SDK's constants do not contain it. The constants stop at their own release. Of the `service.*` attributes, the release that URL names deprecates only `service.peer.name` and `service.peer.namespace` ([changelog](https://raw.githubusercontent.com/open-telemetry/semantic-conventions/v1.45.0/CHANGELOG.md)), so the three the resource sets read the same under either URL.

The instrumentation scope of the renamed spans is `ambrewick.assistant`, and its schema URL is the same as the resource's, which the example asserts. The official client library writes a scope of its own.

**Working rule:** Set `service.name` and `service.version` on the resource yourself, and give `service.instance.id` a value unique to the instance, as the production section explains. Then give the tracer the schema URL of the core release your conventions depend on, from the registry's manifest and not from the SDK's constants, which can lag behind the conventions. Pin the GenAI conventions' version beside the validator, because at v0.1.0 they have no schema URL to stamp.

## Validating against the registry {#validating-against-the-registry}

A name is a claim about the registry, and the validator makes that claim testable. It finds each span's type from `gen_ai.operation.name`, or, for an MCP span, from its method. MCP is the Model Context Protocol, the protocol a tool server speaks. The validator then checks the span's kind and required attributes against the registry's rules. A span whose type it cannot find gets a finding that says so, and each finding names its span, so the output reads as a list of what to fix.

The validator cannot name [chapter 1's spans](#one-message-one-trace), because they carry no `gen_ai.operation.name`, the attribute it reads to find a span's type. Message 809's 4 spans are `message`, `route`, `retrieve` and `answer`, and the check prints one finding for each: `no known span type for this row`. The finding gives the reason. Once the root is renamed, `message` becomes `invoke_agent ambrewick-assistant`, and that span is checked against its own type.

Example `validate-the-spans` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Run the validator over chapter 1's rough spans for message 809: every span fails, because none names a registry span
type.

The point rests on the count of findings, one per span, and on the text of each: "no known span type" means the span
carries neither `gen_ai.operation.name` nor an MCP method, which is how the validator finds a registry span's type."""
from lib.dayrun import RELEASE, run_dev_day
from lib.export import spans_to_rows
from lib.genai import REGISTRY_VERSION, validate
from lib.ids import SequentialIds
from lib.report import fmt_int
from lib.tracing import make_provider, span
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

# Chapter 1 stamped this schema; kept so the spans are the ones chapter 1 printed.
CHAPTER_1_SCHEMA = "https://opentelemetry.io/schemas/1.44.0"

(run,) = run_dev_day(["809"])  # message 809: a route call, a retrieval, and an answer call
outcome = run.outcome
exporter = InMemorySpanExporter()
provider = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", run.clock, SequentialIds(),
                         exporter, CHAPTER_1_SCHEMA)
tracer = provider.get_tracer("ambrewick.assistant")
# Chapter 1's names: the root is the message, each step is named by its step, and no kind is set (INTERNAL).
root = span(tracer, "message", run.arrived_ns, run.replied_ns,
            attributes={"ambrewick.route": outcome.route, "ambrewick.reply.source": outcome.source})
for step in outcome.steps:
    attributes = {"ambrewick.step": step.step}
    if step.step in ("route", "answer"):  # model calls carry their token counts, under the book's own keys
        attributes |= {"ambrewick.tokens.input": step.prompt_tokens, "ambrewick.tokens.cached": step.cached_tokens,
                       "ambrewick.tokens.output": step.completion_tokens}
    span(tracer, step.step, step.start_ns, step.end_ns, parent=root, attributes=attributes)

rows = spans_to_rows(exporter)  # sorted by (trace, start, span), so the findings print in the same order every run
findings = [finding for row in rows for finding in validate(row)]
print("GenAI conventions version:", REGISTRY_VERSION)
print("spans checked:", fmt_int(len(rows)))
for finding in findings:
    print("finding:", finding)
print("findings, no known span type:", fmt_int(sum("no known span type" in finding for finding in findings)))
print("findings, all:", fmt_int(len(findings)))
assert all(len(validate(row)) == 1 for row in rows)  # each span fails once, and only once
```

Output:

```text
GenAI conventions version: 0.1.0
spans checked: 4
finding: message: no known span type for this row
finding: route: no known span type for this row
finding: retrieve: no known span type for this row
finding: answer: no known span type for this row
findings, no known span type: 4
findings, all: 4
```

Renamed, the spans pass. Across all 20 dev-day messages the example checks 74 spans, and it finds 0 problems on any span the registry defines. A single assertion holds that count at zero, so a change that breaks a name fails the run instead of printing a new number.

Example `validate-the-renamed-spans` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Run the validator over every span of the dev day's twenty messages: no finding on any span the registry defines, and
one on each of the book's own fallback spans, which the registry does not define.

The point rests on the line "findings on registry spans: 0", which is asserted, and on the fallback count, which
equals the fallback replies."""
from lib.assistant import Assistant
from lib.bm25 import Retriever
from lib.case import load_articles, load_messages, load_tool_durations
from lib.clock import VirtualClock
from lib.dayrun import DAY, RECORDING, RELEASE
from lib.export import spans_to_rows
from lib.genai import REGISTRY_VERSION, SCHEMA_URL, validate
from lib.ids import SequentialIds
from lib.replay import Replay, ReplayContacts
from lib.report import fmt_int
from lib.tools import Tools
from lib.tracing import make_provider
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from collections import Counter

replay = Replay(RECORDING)
retriever, tools = Retriever(load_articles(), RELEASE.top_k), Tools(load_tool_durations(), ReplayContacts(replay))
messages, fallback_replies, rows = load_messages(DAY), 0, []
for message in messages:  # arrival order, as the replay needs; each message gets its own clock, exporter and trace
    clock = VirtualClock(DAY, start_ns=message.arrival_ns)
    exporter = InMemorySpanExporter()  # one per message, so each message's IDs start from 1
    tracer = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", clock, SequentialIds(),
                           exporter, SCHEMA_URL).get_tracer("ambrewick.assistant", schema_url=SCHEMA_URL)
    fallback_replies += Assistant(replay, retriever, tools, clock, tracer, RELEASE).handle(message).source == "fallback"
    rows += spans_to_rows(exporter)

book = [row for row in rows if row["name"] == "ambrewick.fallback"]
# The book's own fallback span is not a registry span, so it is checked apart from the others.
registry_findings = [finding for row in rows if row["name"] != "ambrewick.fallback" for finding in validate(row)]
book_findings = [finding for row in book for finding in validate(row)]
# A span with no gen_ai.operation.name is counted under its own name, which is how the fallback span appears.
operations = Counter(row["attributes"].get("gen_ai.operation.name", row["name"]) for row in rows)
print("GenAI conventions version:", REGISTRY_VERSION)
print("messages:", fmt_int(len(messages)))
print("spans checked:", fmt_int(len(rows)))
for operation in sorted(operations):
    print(f"spans, {operation}:", fmt_int(operations[operation]))
print("findings on registry spans:", fmt_int(len(registry_findings)))
print("fallback replies:", fmt_int(fallback_replies))
print("findings on the book's fallback span:", fmt_int(len(book_findings)))
assert not registry_findings  # zero findings on every span the registry defines
assert len(book_findings) == len(book) == fallback_replies  # one per fallback span, and each span is a fallback reply
assert all("no known span type" in finding for finding in book_findings)
```

Output:

```text
GenAI conventions version: 0.1.0
messages: 20
spans checked: 74
spans, ambrewick.fallback: 6
spans, chat: 37
spans, execute_tool: 3
spans, invoke_agent: 20
spans, retrieval: 8
findings on registry spans: 0
fallback replies: 6
findings on the book's fallback span: 6
```

The validator does flag other spans. The 6 [fallback replies](#where-the-time-went-in-twenty-messages) each have an `ambrewick.fallback` span, and the check flags all 6 of them, each with `no known span type`. That is correct, and it is not a failure of the conventions. The registry defines the types it names, and a span outside them has no type. The book's own spans and attributes sit in the `ambrewick.` namespace, which is the book's, and the naming rules ask that names sit in a namespace ([naming rules](https://raw.githubusercontent.com/open-telemetry/semantic-conventions/v1.45.0/docs/general/naming.md)). A finding that says a span is outside the registry says the span is the book's own. Each flag is asserted to be that finding and no other, so a registry span that gained a flag would fail the run.

**Working rule:** Read a finding on a registry span as a defect. Read a finding on a span in your own namespace as the registry's answer that the span is yours.

## Name spans in production {#name-spans-in-production}

The validator here runs on recorded spans, inside examples. In production the same check has to run on the spans a service actually exports, and three things make it fail quietly. A fourth decides whether the instance ID means anything. We recommend using a Development name in production when it's pinned and validated, because the validator's first run after an upgrade shows what moved.

The first is the name's content. The specification asks that a span name be "the most general string" for its class of spans, and it marks `get_account/42` as too specific ([span API](https://raw.githubusercontent.com/open-telemetry/opentelemetry-specification/v1.52.0/specification/trace/api.md)). The model span's name carries the model, from a short fixed list, which is general enough. A name built from a user's ID would be a new name for each user, and the registry's pattern has no room for one. A reviewer who sees an identifier in a span name should treat it as a defect, whatever the validator says.

The second is the SDK. It does not stop a wrong name. [Chapter 1's rough names](#spans-by-hand) went through unchanged, and a misspelled registry name would too. Only the validator reads the registry, so a pipeline that exports spans without running it has no check at all. We recommend running the validator in the pipeline that exports spans, not only in tests.

The third is upgrades. A Development name can change in any release, and the validator's first run after an upgrade lists what moved. Read that list before you change the pinned version, and change the names in the same pull request as the version. Spans from another package that writes older names may also reach the same backend. A backend holding those and this book's spans sees two vocabularies for one step.

The fourth is the instance ID. The `service.namespace`, `service.name` and `service.instance.id` triplet MUST be globally unique ([service registry](https://raw.githubusercontent.com/open-telemetry/semantic-conventions/v1.45.0/model/service/registry.yaml)). The SDK's default is a new random UUID in each process. In production, keep that random UUID, or derive a UUIDv5 from an ID unique to the instance, and never share one value across replicas. The replay's fixed instance ID is right for a replay and wrong to copy.

When you add a span, write its registry type first, then its name, then its kind. We recommend this order because the type fixes the name pattern and the kind.

**Working rule:** Run the validator in the pipeline that exports your spans, and fail the build on a finding. Pin the conventions' version beside the check, and read the changelog before you raise it.

## What this chapter decided {#name-spans-decisions}

The registry will move, and the names will move with it. What this chapter fixes is which version the book's spans follow, and a check that reports when they stop following it. Each choice below is one the rest of the book relies on, and an example asserts each one it can.

- The book's names follow GenAI conventions 0.1.0, and the version is pinned beside the validator, because the registry is Development.
- The retrieval span is named by its operation alone, `retrieval`, because the registry's pattern has no place for anything else.
- The provider value is `openai`. That is our judgement, quoted beside the registry's guidance, and the validator cannot check it, because the registry has no value for llama.cpp to check it against.
- The assistant's prompts are named and versioned, so an inference span carries `gen_ai.prompt.name` with `gen_ai.prompt.version`, which the registry makes conditionally required.
- A model span's kind follows the process: CLIENT behind a server, and INTERNAL only in process, when the span names no server.
- The book's resource and tracer carry the schema URL of the core release the registry depends on, not the SDK's newest constant.
- The validator reports a finding on a registry span as a defect, and the book's own fallback spans get findings of their own, which are not defects.

# Let the client library instrument the calls

By the end of this chapter you can read what the official OpenAI instrumentation writes for one chat call, say which of its names differ from the GenAI conventions version 0.1.0 that this book follows, and name the variable that decides whether prompts and replies are recorded, with its default. Chapter 1 wrote the model spans by hand. Chapter 2, "Name spans the way the standard does", gave them the standard's names. This chapter asks whether a library can write those spans instead, and where its spans come out different.

Ambrewick's assistant calls its model through the `openai` client library, and that library has packages that wrap the client and write a span for each call. The model calls are the only steps with recorded times in chapter 1, so a package that writes them correctly would spare the book a large part of its hand-made spans. A package that writes them differently changes every query in the chapters after this one, because those chapters read the names. The question is concrete: for one real call, what does the package emit, and where does it differ from what the book would write by hand?

## A call through the client {#a-call-through-the-client}

There are two ways to get a span for a model call. Manual instrumentation is spans your code makes; automatic instrumentation collects telemetry with no change to the application's source code. Chapter 1 used the first kind. This section uses an instrumentation library. An instrumentation library is a package that makes the telemetry for another library's calls: one call in the start-up code installs it, and the zero-code agent, `opentelemetry-instrument`, loads the same package with no change to the calls.

Example `instrumented-chat-call` (Python 3.13.16 · httpx 0.28.1 · mcp 2.3.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""One chat call through the openai client, instrumented by the official package and answered from the recording. The
point rests on three printed facts: the call makes one client span, named for its operation and model; that span is a
child of the message's span; and it holds the usage the reply reported. The metrics are named and counted here, never
valued, since their durations use real time."""
from lib.http_replay import client, route_body    # lib first: threads and seeds are fixed before anything else

import opentelemetry.sdk.trace as sdk_trace
from opentelemetry.instrumentation.genai.openai import OpenAIInstrumentor
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

from lib.assistant import RELEASES
from lib.case import load_messages
from lib.clock import VirtualClock
from lib.ids import SequentialIds
from lib.names_map import name_map
from lib.report import fmt_int
from lib.tracing import make_provider

clock = VirtualClock("2026-12-07")
# The SDK reads span times from its trace module's time_ns, so patching that name gives every span, the package's included,
# virtual times.
sdk_trace.time_ns = lambda: clock.advance(1_000_000)
exporter, reader = InMemorySpanExporter(), InMemoryMetricReader()
provider = make_provider("ambrewick-assistant", RELEASES["r0"].service_version, "example", clock, SequentialIds(),
                         exporter, "https://opentelemetry.io/schemas/1.45.0")
OpenAIInstrumentor().instrument(tracer_provider=provider, meter_provider=MeterProvider(metric_readers=[reader]))

with provider.get_tracer("ambrewick-assistant").start_as_current_span("invoke_agent ambrewick-assistant"):
    reply = client().chat.completions.create(**route_body(load_messages("2026-12-07")[0]))

call, root = exporter.get_finished_spans()                  # the call ends before the message's span does
metrics = reader.get_metrics_data().resource_metrics[0].scope_metrics[0].metrics
print("spans in the trace:", len(exporter.get_finished_spans()))
print("instrumented span, name:", call.name)
print("instrumented span, kind:", call.kind.name)
print("instrumented span, scope schema URL:", call.instrumentation_scope.schema_url)
print("attributes on the span:", ", ".join(sorted(call.attributes)))
print("gen_ai.provider.name on the span:", call.attributes["gen_ai.provider.name"])
print("server.address on the span:", call.attributes["server.address"])
print("server.port on the span:", call.attributes["server.port"])
print("input count on the span:", fmt_int(call.attributes["gen_ai.usage.input_tokens"]))
print("output count on the span:", fmt_int(call.attributes["gen_ai.usage.output_tokens"]))
for metric in metrics: print(f"metric {metric.name}, unit {metric.unit.strip('{}')}, data points: {len(metric.data.data_points)}")
types = {p.attributes["gen_ai.token.type"] for m in metrics if m.name == "gen_ai.client.token.usage" for p in m.data.data_points}
print("token types on the usage metric:", ", ".join(sorted(types)))
# The call is a child of the message's span, and its usage is the reply's. Every name it makes is in the table.
assert call.parent.span_id == root.context.span_id
assert (call.attributes["gen_ai.usage.input_tokens"], call.attributes["gen_ai.usage.output_tokens"]) == (
    reply.usage.prompt_tokens, reply.usage.completion_tokens)
assert {m.name for m in metrics} | set(call.attributes) | {"gen_ai.token.type"} <= set(name_map())
```

Output:

```text
spans in the trace: 2
instrumented span, name: chat qwen3-4b-instruct-2507
instrumented span, kind: CLIENT
instrumented span, scope schema URL: https://opentelemetry.io/schemas/1.37.0
attributes on the span: gen_ai.operation.name, gen_ai.provider.name, gen_ai.request.max_tokens, gen_ai.request.model, gen_ai.request.seed, gen_ai.request.temperature, gen_ai.response.finish_reasons, gen_ai.response.id, gen_ai.response.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, server.address, server.port
gen_ai.provider.name on the span: openai
server.address on the span: localhost
server.port on the span: 8000
input count on the span: 142
output count on the span: 6
metric gen_ai.client.operation.duration, unit s, data points: 1
metric gen_ai.client.token.usage, unit token, data points: 2
token types on the usage metric: input, output
```

The run sends one route request through the `openai` client: the route call for the dev day's first message, which `load_messages(...)[0]` replays. The client does not reach a model. Its HTTP exchange is a recording, served by the mock transport of `httpx` from `lib/http_replay.py`. The transport answers every request, so no socket opens even though the URL names the model server. The recorded server sends usage only on a non-streamed reply, so the recording keeps that reply, and a span takes its [token counts](#three-token-counts) from usage. The run also patches the `time_ns` in the SDK's trace module, which the package's spans take their times from, so the call's span gets the virtual times the replay gives. [Replay and the virtual clock](#replay-and-the-virtual-clock) explains the rest. The package's duration [metrics](#totals-from-metrics-not-spans) are not patched, and [what the package emits](#what-the-package-emits) says why.

The trace holds 2 spans: the message's root, `invoke_agent ambrewick-assistant`, and the call. The package marks the call CLIENT, as the book marks its own model calls, because the model runs behind a server. The call's span is named `chat qwen3-4b-instruct-2507`, the operation followed by the model, which is the registry's pattern for an inference span.

The call's usage reads 142 [input tokens](#three-token-counts) and 6 [output tokens](#three-token-counts). These are the usage counts the llama-cpp-python server reported in its reply, which the package copied onto the span. They are not the book's recorded counts, which re-tokenize the prompt. The attribute's name, `gen_ai.usage.input_tokens`, says what the value counts, not where it came from.

The book's code makes only the root; the package makes the call's span inside it. The script asserts that the call's parent is the root, and that its two usage counts equal the reply's, so a change in either fails the run.

**Working rule:** Wrap the client once, at start-up, and make your own spans only for work the library cannot see, such as the message's root, its tool calls and its fallback reply. When no package wraps a client, or the one that does writes names the table can't map, make the call's span by hand, as chapter 1 did. Then check the call's parent in a test, as the script does, because the parent is what places the call in its message's trace.

## What the package emits {#what-the-package-emits}

The package writes one span per call, named for the operation and the model, and the output lists the attribute names on that span in sorted order. The ones this book reads are `gen_ai.operation.name`, `gen_ai.provider.name`, `gen_ai.request.model`, `gen_ai.response.model`, `gen_ai.response.finish_reasons`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `server.address` and `server.port`. The provider value is openai, the value chapter 2 gives the book's own spans for an `openai` client.

One difference from the book's own spans shows in that list: content. No attribute holds a prompt or a reply, because content capture is off. [The capture switch](#the-capture-switch) says what that switch is and what its default is. The package takes `server.port` from the client's base URL, and leaves it out when that port is implicit or is 443 (`opentelemetry/instrumentation/genai/openai/utils.py` at 1.3b0).

The call makes two metrics, and the output gives their names, units and point counts. `gen_ai.client.operation.duration`, in seconds, has 1 data point. `gen_ai.client.token.usage`, in tokens, has 2 data points, one for input and one for output. The points are split by `gen_ai.token.type`, which is the older conventions' name for that split. It is still a deprecated constant in `opentelemetry-semantic-conventions` 0.66b2, and v0.1.0 replaced it with the two token histograms. In this chapter, "metric" and "[histogram](#totals-from-metrics-not-spans)" name the package's instruments only. Chapter 6 defines both.

A streamed call adds two more instruments, `gen_ai.client.operation.time_to_first_chunk` and `gen_ai.client.operation.time_per_output_chunk`, and one span attribute, `gen_ai.response.time_to_first_chunk`. This chapter's example does not stream, so its output prints none of them. The name table holds all three stream names, which the generator observed from the streamed reply it builds, as [hand-made spans against the instrumented ones](#hand-made-against-instrumented) explains.

The chapter prints each instrument's name, unit and point count, and no value, for one reason. The package takes its span times from the clock the script patches, but its duration and chunk instruments read a monotonic timer that the patch does not reach. Their values are therefore the recording machine's real timings, and they change on every run. The token values are fixed, because they are the reply's usage, and they print as counts so that every instrument prints the same way.

**Working rule:** Count a package's spans and its instruments in a test, and read each name, unit and point count from its output. Do not assert a value from an instrument whose timer your tests do not control, because the count holds on every run and the value does not.

## Hand-made spans against the instrumented ones {#hand-made-against-instrumented}

Chapter 2 checks the book's own spans against the registry, and this section measures the package the same way. The names are observed from the package's output, and the mapping to v0.1.0 is the book's judgement, written once in the generator, `examples/data/genai/build_names_map.py`, and checked against the registry. The output came from the recorded call, from a streamed reply that the generator builds for the names a stream adds, and from a call with content events on, which gives the name of the event. One entry comes from the package's source rather than from a run: `gen_ai.usage.cache_read.input_tokens`. The package writes it only when a reply carries cached prompt tokens, and the recorded replies carry none.

Example `diff-hand-and-instrumented` (Python 3.13.16 · numpy 2.5.5), passing in Edition 2026.11.2:

```python
"""The names the official package emits, set against the GenAI conventions v0.1.0 names this book uses. The table is
examples/lib/names_map.py, which examples/data/genai/build_names_map.py writes by running the package on the recorded
call, on a streamed reply it constructs (for the names a stream adds) and on a call with content events on (for the
event's name). The point rests on
the last printed count: five names differ from v0.1.0, and each one is named here. instrumented-chat-call checks that
the names a live call makes are in the same table."""
from lib.names_map import REGISTRY_VERSION, name_map          # lib first: threads and seeds are fixed before anything else
from importlib.metadata import version

table = name_map()


def status(name, targets):
    """Same when the name is its own v0.1.0 name, or the chat span's type; the two named exceptions get their own
    labels, and the rest are renamed, split or absent."""
    if targets == (name,) or (name == "chat {model}" and targets == ("gen_ai.client.inference",)):
        return "same"
    if name == "gen_ai.client.operation.duration":
        return "wrong instrument for inference"
    if name == "gen_ai.token.type":
        return "replaced by the two token histograms"
    if not targets:
        return "no v0.1.0 name"
    return "split into two" if len(targets) == 2 else "renamed"


statuses = {name: status(name, targets) for name, targets in table.items()}
print("registry version:", REGISTRY_VERSION)
print("package version:", version("opentelemetry-instrumentation-genai-openai"))
print("names the package emits, in the table:", len(table))
print("names the same in v0.1.0:", sum(value == "same" for value in statuses.values()))
for name in sorted(table):
    if statuses[name] != "same":
        print(f"{statuses[name]}, {name}:", " and ".join(table[name]) or "none")
print("names that differ from v0.1.0:", sum(value != "same" for value in statuses.values()))
assert {name for name, value in statuses.items() if value != "same"} == {
    "gen_ai.client.operation.duration", "gen_ai.client.token.usage", "gen_ai.client.operation.time_to_first_chunk",
    "gen_ai.client.operation.time_per_output_chunk", "gen_ai.token.type"}
```

Output:

```text
registry version: 0.1.0
package version: 1.3b0
names the package emits, in the table: 25
names the same in v0.1.0: 20
wrong instrument for inference, gen_ai.client.operation.duration: gen_ai.client.inference.duration
renamed, gen_ai.client.operation.time_per_output_chunk: gen_ai.client.inference.time_per_output_chunk
renamed, gen_ai.client.operation.time_to_first_chunk: gen_ai.client.inference.time_to_first_chunk
split into two, gen_ai.client.token.usage: gen_ai.client.inference.operation.input_tokens and gen_ai.client.inference.operation.output_tokens
replaced by the two token histograms, gen_ai.token.type: none
names that differ from v0.1.0: 5
```

The table holds 25 names that the package emits. Of those, 20 are the same in v0.1.0, and 5 differ. Each of the five that differ is printed with what it became in v0.1.0.

Four of the five differences are in metrics. The registry's metrics file says `gen_ai.client.operation.duration` SHOULD NOT be reported for inference, and it names the inference duration `gen_ai.client.inference.duration`. The token metric is the one that splits: where the package writes one histogram with a `gen_ai.token.type` point attribute, the registry has two histograms, one for input and one for output. The fifth, `gen_ai.token.type`, is the name the older conventions gave that split, and v0.1.0 replaced it with the two token histograms, so a query written from the registry cannot select the package's input points with it.

Because chapter 2 checked the book's own spans against the registry, every gap in this table belongs to the package. The table is what chapters 6 and 7 use when they read a package's output. The first uses are [`totals-from-metrics-not-spans`](#totals-from-metrics-not-spans) in chapter 6 and [`time-to-first-chunk`](#time-to-first-chunk) in chapter 7.

**Working rule:** Keep one table of the names a package emits, generated from its output and checked against the registry, and read the package's data through it. A query for a name the table lacks should fail in the test, as the book's examples fail, and not return nothing in production. Regenerate the table when the package's version changes, not when a chart goes quiet.

## Three packages called openai {#the-three-openai-packages}

Three packages called `openai` instrument the client, and they differ on names and on content. Their names, as PyPI spells them, are `opentelemetry-instrumentation-genai-openai`, `opentelemetry-instrumentation-openai-v2` and `opentelemetry-instrumentation-openai`. The first two are OpenTelemetry's. The third is Traceloop's. Only the first is installed here, at the version the pins hold. The other two are neither installed nor pinned, so this section reads their published wheels, at the versions and dates the table gives, and does not run them. Their versions are written as text for that reason: the pins file does not hold them, and no example prints them.

Example `three-openai-packages` (Python 3.13.16 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0), passing in Edition 2026.11.2:

```python
"""Three packages called openai instrument the client, and they disagree on names and on content. Two are OpenTelemetry's
and differ in naming scheme; the third is Traceloop's and captures content by default. Only the first is installed in the
pinned environment, so the point rests on that one: its version is printed, and the module that reads its content switch
names the switch the table gives. The other two are not importable here, so their names and defaults are the source
readings the chapter cites, printed as wheel readings and not as runs."""
import lib  # lib first: threads and seeds are fixed before anything else

import importlib.util
from importlib.metadata import version

# Name as PyPI spells it; the module it imports; its project; the naming its source gives; its content switch and that
# switch's default, both from the source reading in notes/research/client-library-instrumentation.md (S2, S6, S7).
PACKAGES = (
    ("opentelemetry-instrumentation-genai-openai", "opentelemetry.instrumentation.genai.openai", "OpenTelemetry",
     "GenAI conventions, latest experimental, unconditionally", "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT",
     "NO_CONTENT"),
    ("opentelemetry-instrumentation-openai-v2", "opentelemetry.instrumentation.openai_v2", "OpenTelemetry",
     "GenAI conventions v1.30.0 unless the experimental opt-in is set", "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT",
     "false"),
    ("opentelemetry-instrumentation-openai", "opentelemetry.instrumentation.openai", "Traceloop",
     "its own names, from opentelemetry-semantic-conventions-ai 0.5.1", "TRACELOOP_TRACE_CONTENT", "true"),
)
installed = [row for row in PACKAGES if importlib.util.find_spec(row[1]) is not None]
assert [row[0] for row in installed] == ["opentelemetry-instrumentation-genai-openai"]
source = importlib.util.find_spec("opentelemetry.util.genai.utils").origin
assert installed[0][4] in open(source, encoding="utf-8").read()     # the module that reads the switch names it

print("packages importable in this environment:", len(installed))
print("installed version:", version(installed[0][0]))
for name, module, project, naming, switch, default in PACKAGES:
    print(f"{name}, evidence:", "installed source" if name == installed[0][0] else "wheel reading")
    print(f"{name}, project:", project)
    print(f"{name}, naming:", naming)
    print(f"{name}, content switch:", switch)
    print(f"{name}, content switch default:", default)
```

Output:

```text
packages importable in this environment: 1
installed version: 1.3b0
opentelemetry-instrumentation-genai-openai, evidence: installed source
opentelemetry-instrumentation-genai-openai, project: OpenTelemetry
opentelemetry-instrumentation-genai-openai, naming: GenAI conventions, latest experimental, unconditionally
opentelemetry-instrumentation-genai-openai, content switch: OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT
opentelemetry-instrumentation-genai-openai, content switch default: NO_CONTENT
opentelemetry-instrumentation-openai-v2, evidence: wheel reading
opentelemetry-instrumentation-openai-v2, project: OpenTelemetry
opentelemetry-instrumentation-openai-v2, naming: GenAI conventions v1.30.0 unless the experimental opt-in is set
opentelemetry-instrumentation-openai-v2, content switch: OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT
opentelemetry-instrumentation-openai-v2, content switch default: false
opentelemetry-instrumentation-openai, evidence: wheel reading
opentelemetry-instrumentation-openai, project: Traceloop
opentelemetry-instrumentation-openai, naming: its own names, from opentelemetry-semantic-conventions-ai 0.5.1
opentelemetry-instrumentation-openai, content switch: TRACELOOP_TRACE_CONTENT
opentelemetry-instrumentation-openai, content switch default: true
```

The output gives each package's project, its naming, its content switch and that switch's default, and it says for each package whether those lines come from the installed source or from a wheel reading. The script checks that `opentelemetry.util.genai.utils`, the module that reads the switch, names the first package's switch.

| Package, version and date | Project | Names | Content switch, default |
| --- | --- | --- | --- |
| `opentelemetry-instrumentation-genai-openai`, 1.3b0, 23 October 2026 | OpenTelemetry | GenAI conventions, experimental set | `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT`, `NO_CONTENT` |
| `opentelemetry-instrumentation-openai-v2`, 2.4b0, 1 May 2026 | OpenTelemetry | GenAI conventions v1.30.0, unless opted in | `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT`, `false` |
| `opentelemetry-instrumentation-openai`, 0.63.1, 16 November 2026 | Traceloop | its own names, from `opentelemetry-semantic-conventions-ai` 0.5.1 | `TRACELOOP_TRACE_CONTENT`, `true` |

The first package's page calls its version a pre-release, and its description says, "The latest experimental features may introduce breaking changes in future releases." The page also says that it uses the experimental GenAI conventions unconditionally, with no opt-in and no version named. The page names no conventions version, but the scope stamps https://opentelemetry.io/schemas/1.37.0, beside the book's 1.45.0. The table names no version of the conventions for the first package, because the package states none, and [the earlier section](#hand-made-against-instrumented) measures it against v0.1.0, the version the book follows.

The second package keeps the older naming by default, and its switch has two meanings. On its legacy path the variable takes `true`, and the default is `false`. On its experimental path the variable takes `span_only`, `event_only` or `span_and_event`. Which meaning applies depends on the experimental opt-in, so a team reads the package's version and its opt-in together before it sets the variable. Both OpenTelemetry packages read the same variable, with different values, so a team that moves from the second and keeps `true` gets `NO_CONTENT` from the first, with only a warning in the log.

Traceloop's package names its span `openai.chat`, not the operation and the model, and it writes prompts and completions into the span by default. Its switch is `TRACELOOP_TRACE_CONTENT`, and it stays on unless someone sets it to `false`. Any value other than `true`, `1`, `yes` or `on` turns it off, and a context value, `override_enable_content_tracing`, turns it back on. That is the reverse of the OpenTelemetry package, and it is the difference that matters most in this chapter. A team that adds Traceloop's package to a service that sends private text to a model has changed what its telemetry holds, and it has not set any variable to do so.

For this book we use the first package. It is the one the pins hold, and its names are the registry's, bar the five differences in [the earlier section](#hand-made-against-instrumented). We would choose the second only for a [backend](#otlp-over-http) that reads its older names and nothing else, and the third only for the names its own project defines. Either choice needs its content switch read at the version pinned, with content capture off unless someone turned it on for a stated purpose.

**Working rule:** Read each instrumentation package's content switch and its default from that package's own source or documentation at the version you pin, and not from the spec alone. The defaults differ between packages, so a service that adds a second package changes what its telemetry can hold.

## The capture switch {#the-capture-switch}

Content capture is the instrumentation's switch for recording prompts and replies themselves, and it is off, `NO_CONTENT`, unless set. The first package's default is `NO_CONTENT` and the second's is `false`; Traceloop's 0.63.1 wheel turns it on ([Three packages called openai](#the-three-openai-packages)).

The GenAI conventions v0.1.0 spans page says the switch MUST be named `OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT`, and the first package departs from that MUST. It reads a different variable, `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT`, and reads the spec's name nowhere. The next run shows what that does. It sets the spec's name to `SPAN_ONLY` and makes one call. Then it does the same with the package's own name, as a control, and counts the content attributes each call's span holds.

Example `capture-switch-names` (Python 3.13.16 · httpx 0.28.1 · mcp 2.3.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""The content switch: whether the official package's span holds the prompt and the reply. The package reads one variable,
and the spec's name for the same switch is read nowhere in the package. The point rests on three counts. With the spec's
name set to SPAN_ONLY, one call's span holds no content. With the package's own name set to SPAN_ONLY, a control call's
span holds two, so the count can rise and the package does read its name. And the package's parser gives NO_CONTENT when
its variable is unset and when it holds a value that is not a mode. The control records content for one call, and this
example prints only how many content attributes that span holds, never their values."""
import lib  # lib first: threads and seeds are fixed before anything else

import os

import opentelemetry.sdk.trace as sdk_trace
from opentelemetry.instrumentation.genai.openai import OpenAIInstrumentor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.util.genai.utils import ContentCapturingMode, get_content_capturing_mode

from lib.assistant import RELEASES
from lib.case import load_messages
from lib.clock import VirtualClock
from lib.http_replay import client, route_body
from lib.ids import SequentialIds
from lib.tracing import make_provider

PACKAGE_VARIABLE = "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"
SPEC_VARIABLE = "OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT"
print("the package reads:", PACKAGE_VARIABLE, "| the spec's name for the switch:", SPEC_VARIABLE)
print("values the package parses:", ", ".join(mode.name for mode in ContentCapturingMode))
os.environ.pop(PACKAGE_VARIABLE, None)
print("mode, package variable unset:", get_content_capturing_mode().name)
os.environ[PACKAGE_VARIABLE] = "not a mode"                   # the parser logs this and falls back, it does not raise
print("mode, value that is not a mode:", get_content_capturing_mode().name)
os.environ.pop(PACKAGE_VARIABLE)


# Instrument afresh with the variable set to SPAN_ONLY, make one call, and print how many content attributes its span
# holds. The package reads its mode when it is instrumented, so the variable is set before that and removed after.
def content_attributes(variable: str, label: str, expected: int) -> None:
    os.environ[variable] = "SPAN_ONLY"
    clock = VirtualClock("2026-12-07")
    sdk_trace.time_ns = lambda: clock.advance(1_000_000)      # virtual span times, as in instrumented-chat-call
    exporter = InMemorySpanExporter()
    provider = make_provider("ambrewick-assistant", RELEASES["r0"].service_version, "example", clock, SequentialIds(),
                             exporter, "https://opentelemetry.io/schemas/1.45.0")
    instrumentor = OpenAIInstrumentor()
    instrumentor.instrument(tracer_provider=provider)
    client().chat.completions.create(**route_body(load_messages("2026-12-07")[0]))
    instrumentor.uninstrument()
    os.environ.pop(variable)
    call = exporter.get_finished_spans()[0]
    count = len([key for key in call.attributes if key.startswith(("gen_ai.input.messages", "gen_ai.output.messages"))])
    print(f"content attributes on the span, {label}:", count)
    assert count == expected


content_attributes(SPEC_VARIABLE, "spec variable set", 0)     # set, and read by nothing in the package
content_attributes(PACKAGE_VARIABLE, "package variable set", 2)   # the control: the package's own name, one call
```

Output:

```text
the package reads: OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT | the spec's name for the switch: OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT
values the package parses: NO_CONTENT, SPAN_ONLY, EVENT_ONLY, SPAN_AND_EVENT
mode, package variable unset: NO_CONTENT
mode, value that is not a mode: NO_CONTENT
content attributes on the span, spec variable set: 0
content attributes on the span, package variable set: 2
```

The point is the difference between two counts: the spec's name gives 0 content attributes, where the package's own name gives 2, and nothing reports the difference. A team that sets the spec's name gets the output it would get with no setting at all, and that is the failure to guard against. It is quiet, and it looks like success until someone asks for a prompt and finds none.

The package parses four values: `NO_CONTENT`, `SPAN_ONLY`, `EVENT_ONLY` and `SPAN_AND_EVENT`. The package's source at 1.3b0 (`opentelemetry/util/genai/utils.py`) upper-cases the value before it matches a mode, so the match ignores letter case. For anything else it logs a warning and returns `NO_CONTENT`. The output shows both fallbacks. With the package's variable unset, the mode is NO_CONTENT. With a value that is not a mode, it is NO_CONTENT.

Chapter 12, in [What leaks when capture is on](#what-leaks-when-capture-is-on), says what each of the four modes writes and leaks. Here one call records content as a control, and that example prints only how many content attributes its span holds. Every other example in this chapter runs with capture off, and the book keeps it off until chapter 12 turns it on for a stated purpose.

A second switch, `OTEL_INSTRUMENTATION_GENAI_COMPLETION_HOOK`, can upload content to files and write references to them. The package writes those references as `gen_ai.input.messages_ref` and `gen_ai.output.messages_ref`, the registry's names; only the instrumentation's docstring spells them with dots. No run in this chapter emits either one, because the hook also needs `OTEL_INSTRUMENTATION_GENAI_UPLOAD_BASE_PATH` set, and no run here sets it. Chapter 12 meets the hook.

**Working rule:** Set a package's content variable by the name its own source reads, at the version you pin, and check the setting in a test that asserts the span holds content exactly when the variable names a mode that records it. Leave content capture off in any service that has not named a purpose for it, and read the default of every package the service loads.

## Two other naming schemes {#two-other-naming-schemes}

Two more naming schemes describe the same facts as the GenAI conventions: OpenInference, which Arize publishes, with its own `openinference-instrumentation-openai` package as a fourth package for the client, and OpenLLMetry, the project behind Traceloop's package. We describe both so that a reader who meets their names knows what they stand for. The book emits neither.

OpenInference's module, at its pinned version `0.1.46`, names the model, the provider, the token counts, the span kind and the messages in its own constants. The script reads those constants and sets each one beside the GenAI name for the same fact.

Example `openinference-mapping` (Python 3.13.16 · numpy 2.5.5 · openinference-semantic-conventions 0.1.46), passing in Edition 2026.11.2:

```python
"""OpenInference, a naming scheme the book does not emit, at its pinned version. Its module names the facts a model call
carries (the model, the provider, the token counts, the span kind, the messages) in its own words. The point rests on
the table: each name is one the pinned module defines, and each maps to a GenAI conventions name the book's registry or
its name table holds. The mapping is written here by hand, and checked against both."""
import lib  # lib first: threads and seeds are fixed before anything else

from importlib.metadata import version

from openinference.semconv.trace import OpenInferenceLLMSystemValues, OpenInferenceSpanKindValues, SpanAttributes

from lib import genai
from lib.names_map import NAMES

# OpenInference's constant and the GenAI name for the same fact. OpenInference's span kind has no GenAI attribute: the
# operation name carries the same meaning, chat for a model call.
MAPPING = (
    (SpanAttributes.LLM_MODEL_NAME, "gen_ai.request.model"),
    (SpanAttributes.LLM_SYSTEM, "gen_ai.provider.name"),
    (SpanAttributes.LLM_TOKEN_COUNT_PROMPT, "gen_ai.usage.input_tokens"),
    (SpanAttributes.LLM_TOKEN_COUNT_COMPLETION, "gen_ai.usage.output_tokens"),
    (SpanAttributes.LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_READ, "gen_ai.usage.cache_read.input_tokens"),
    (SpanAttributes.OPENINFERENCE_SPAN_KIND, "gen_ai.operation.name"),
    (SpanAttributes.LLM_INPUT_MESSAGES, "gen_ai.input.messages"),
    (SpanAttributes.LLM_OUTPUT_MESSAGES, "gen_ai.output.messages"),
)
known = set(genai.ATTR) | {name for names in NAMES.values() for name in names}
print("openinference-semantic-conventions version:", version("openinference-semantic-conventions"))
for openinference, conventions in MAPPING:
    print(f"{openinference} -> {conventions}")
    assert conventions in known
print("span kind for a model call:", OpenInferenceSpanKindValues.LLM.value)
print(f"{SpanAttributes.LLM_SYSTEM} for an OpenAI client:", OpenInferenceLLMSystemValues.OPENAI.value)
```

Output:

```text
openinference-semantic-conventions version: 0.1.46
llm.model_name -> gen_ai.request.model
llm.system -> gen_ai.provider.name
llm.token_count.prompt -> gen_ai.usage.input_tokens
llm.token_count.completion -> gen_ai.usage.output_tokens
llm.token_count.prompt_details.cache_read -> gen_ai.usage.cache_read.input_tokens
openinference.span.kind -> gen_ai.operation.name
llm.input_messages -> gen_ai.input.messages
llm.output_messages -> gen_ai.output.messages
span kind for a model call: LLM
llm.system for an OpenAI client: openai
```

The example prints each OpenInference name beside its GenAI name, and the run checks every pair against the name table, so a constant that moves at the next pin fails the run. The token counts are the pairs a reader meets first: `llm.token_count.prompt` pairs with `gen_ai.usage.input_tokens`, and `llm.token_count.completion` with `gen_ai.usage.output_tokens`.

The script asserts that each GenAI name is one the book's [name table](#hand-made-against-instrumented) holds, so a mapping that names a missing name fails the run. OpenInference's span kind has no GenAI attribute of its own. The output records that a model call is `LLM` in OpenInference, and the operation name carries the same meaning in the GenAI names, as `chat`. Its OpenAI provider value is `openai`, the same string the first OpenTelemetry package writes for an `openai` client.

OpenLLMetry's names come from `opentelemetry-semantic-conventions-ai`, version 0.5.1, released 26 March 2026, which Traceloop's 0.63.1 package uses. The caveat about these readings is in [Three packages called openai](#the-three-openai-packages). Four of OpenLLMetry's names have a registry name that does the same job: `gen_ai.client.operation.duration` for `gen_ai.client.inference.duration`, `gen_ai.client.token.usage` for the input and output histograms, `gen_ai.usage.cache_creation.input_tokens` for `gen_ai.usage.cache_write.input_tokens`, and `gen_ai.usage.reasoning_tokens` for `gen_ai.usage.reasoning.output_tokens`.

We recommend the OpenTelemetry names throughout this book. The backends that chapter 5, [What others do](#what-others-do), describes say they ingest those names, and each claim is given there with its version and date. Choose a scheme for another reason only when a backend you run reads that scheme and nothing else. Do not mix schemes in one trace. A query for `gen_ai.usage.input_tokens` finds no span that writes `llm.token_count.prompt`, and its total comes out short, with no [error](#how-a-span-records-failure) to say so.

**Working rule:** Map each scheme's names onto the registry's once, in a table in code, and fail the run for any name the table does not hold, as the mapping example above does. Choose one scheme for a service's spans before the first span is sent, and keep the names of the others out of its traces.

## What goes wrong in production {#client-library-instrumentation-in-production}

Four things go wrong with the package in production.

- **The pre-release.** The first package is at a pre-release version, and its page warns that its experimental features may change without notice. The pin holds one version. A team that upgrades takes whatever names the next release writes, so the name table must be regenerated, and the run must fail on a name it does not hold.
- **The switch in the wrong place.** The spec's name does nothing with this package, and no error says so. The opposite mistake is worse. A team that adds Traceloop's package and sets nothing has turned prompt capture on, because that package's default is on, in its 0.63.1 wheel, and a context override can turn it back on even when the variable is `false`.
- **Dashboards on the registry's names.** A chart that reads `gen_ai.client.inference.duration` from this package finds no points, since the package writes `gen_ai.client.operation.duration`. [The earlier section](#hand-made-against-instrumented) lists each name that differs.
- **Two packages on one client.** A service that loads a second instrumentation package for the same client may write each call's span twice, under two sets of names. No example here loads two, so this is not shown; a test that counts spans per call would show it.

## The decisions this chapter made {#client-library-instrumentation-decisions}

A package's names lag the standard, and each choice below says how the book lives with that:

- The model calls are wrapped by the OpenTelemetry package pinned at 1.3b0, and the book's own spans wrap only the work the package cannot see.
- The five names that the package writes differently from the registry are mapped once, in a generated table, and the rest of the book reads the package's output through that table.
- Content capture is off in every example in this chapter except one control, which records content for one call and prints only its count. Chapter 12 turns it on, on purpose, and says what it leaks.
- Metrics are printed by name, unit and point count, and never by value, because their duration instruments use real time.
- The book uses the OpenTelemetry names because they are the ones the backends in [chapter 5](#what-others-do) say they ingest, so [changing the backend](#changing-backends) is a change of settings, not of spans.
- The three package names are given exactly, and only the first is run. The other two are wheel readings, as [the section on the three packages](#the-three-openai-packages) explains.

**Working rule:** Pin the instrumentation package at its exact version, generate its name table from its own output, and read its content switch from its source at that version before you trust the content a span holds. A package that changes its names or its defaults changes what your traces hold, and its version and its scopes' schema URL are the signals you get that it has.

# Follow a request across processes

By the end of this chapter you can make a span that another team's server writes join the trace of the message that caused it, check that it has joined, and find the spans that have not. The problem starts with one request. Message 16297 on baseline day 1, a recorded day of 200 messages, asks about a contact, so the router sends it to the `messages` route, which calls `find_contact`. That tool runs on the contacts team's MCP server, a separate process that the assistant starts and talks to over stdio, and the server writes its own spans. Until those spans carry the message's trace ID and name the call that asked for them, the trace stops at the tool step, and nothing says which message the lookup served.

The lookup is replayed on the recording machine, a 4-vCPU Intel Xeon at 2.10 GHz, with the virtual clock from [Replay and the virtual clock](#replay-and-the-virtual-clock). So this chapter makes the server's spans join the message's trace, and builds the counts that find the ones that don't.

## The contacts server is another process {#the-contacts-server}

The assistant does not run `find_contact` itself. The contacts team owns the server, and the mcp package at 2.3.0 starts it as a subprocess and sends it requests over standard input and output, the transport the specification calls stdio. Because the server is its own process, its spans never enter the assistant's memory: it writes them to a JSON-lines file of its own, which the assistant reads once the process has exited. The MCP SDK makes a span for each request it sends, and [Trace calls with OpenTelemetry](https://rollingedition.com/model-context-protocol-in-practice/s/trace-with-opentelemetry) covers those spans in depth. The join is what ties the server's spans to the message. A request that loses its header leaves the server's work in the file with no link to the question that caused it.

The other tools in the case do not have this problem. The calendar, alarm and list tools run inside the assistant's own process, so their spans are made in the same memory, and they join the trace by the ordinary parent link that [One message, one trace](#one-message-one-trace) showed.

This chapter calls the contacts server's life a run, not a session. The [2026-07-28 revision of the Model Context Protocol specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/index) says that an open connection, such as a stdio process, is not a conversation or a session, and a server must not treat it as one. The replay starts one process for each run, inside a `contacts startup` span, and every message the run answers reuses it, so a run has one process and one span file, read after the run ends. Nothing carries over from one run to the next, because each run starts its own process. That is the replay's choice, as the MCP specification's statelessness section recommends. In production, a client should not tie the process's life to one task, thread or conversation. Start one process per run and reuse it across messages, as `propagate-into-the-tool` does with its two calls. A server that outlives a run cannot be read at exit, so it needs a flush or a receiver, which [The book's receiver](#the-book-receiver) provides.

The recording shows the failure this section is about. Baseline day 1 was recorded with a client that had no tracer provider, so the client sent no context. The example reads that recording.

Example `server-span-without-context` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Read baseline day 1's recorded contacts-server spans for message 16297. The recorder's client sent no context, so the
server's lookup span has no parent and starts a trace of its own: a detached root. The prose's two counts rest on the
printed lines, and the assert backs the parent count."""
from lib.dayrun import DATA
import json

rows = [json.loads(line) for line in (DATA / "baseline-day-1" / "contacts-spans.jsonl").read_text(encoding="utf-8").splitlines()]
lookups = [r for r in rows if r["name"] == "tools/call find_contact"]
with_parent = [r for r in lookups if r["parent_span_id"] is not None]
lookup = next(r for r in rows if r["name"] == "contacts.lookup")
call = lookups[0]
assert with_parent == [] and lookup["parent_span_id"] == call["span_id"] and lookup["trace_id"] == call["trace_id"]
print("tools/call find_contact spans in the contacts server:", len(lookups))
print("of them with a parent:", len(with_parent))
print("contacts.lookup under it, in its trace: yes")
```

Output:

```text
tools/call find_contact spans in the contacts server: 3
of them with a parent: 0
contacts.lookup under it, in its trace: yes
```

The file holds 3 `tools/call find_contact` spans, and 0 of them have a parent. The lookup's own span still sits under its call in the server's file. But a call with no parent is a detached root (defined in [Context is lost at a thread boundary](#lost-context)), so nothing ties it to the message.

**Working rule:** Give each server process its own tracer provider and exporter, and read its span file only after the process has exited. The server uses `SimpleSpanProcessor`, which hands each span to the exporter when the span ends, so a file read after exit holds every span the server made. A `BatchSpanProcessor` keeps spans in a queue until a flush or a shutdown, so with one, the file is complete only after one of those.

## The MCP SDK writes traceparent into _meta {#traceparent-in-meta}

For a server span to join the trace, the request has to carry the trace's identity, and MCP gives each request a `_meta` object beside its arguments for that. The field that holds the identity is defined by [W3C Trace Context](https://www.w3.org/TR/2021/REC-trace-context-1-20211123/), a Recommendation of 23 November 2021. Its `traceparent` header has four fields joined by hyphens: a version, a trace ID, a parent span ID and flags. The trace ID is 32 hexadecimal digits and the parent ID 16; all-zero values of either are invalid. The flags carry the sampled decision, which chapter 11 uses in [parent-based sampling](#parent-based-sampling).

Context propagation carries the context, the span's identity and any [baggage](#what-goes-in-baggage), to the next process; `traceparent` is the W3C field for the span's part: the trace ID, the parent's span ID and the trace flags, of which the sampled flag is the only one defined. A span's context has more in it, the trace state among other things, but those three are the part a server needs to attach its span under the right parent.

The first thing to try is to write the header yourself, and see what the server does with it. Below, one call carries a header that names a trace this assistant never made, and a second call asks for a tool the server does not have.

Example `propagate-into-the-tool` (Python 3.13.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Write a traceparent into one call to the contacts server, then ask for a tool the server does not have. The prose's claim
that the SDK replaces the header rests on the second printed line, and its claim about the unknown tool on the third."""
from lib.clock import VirtualClock
from lib.contacts_server import SPANS_ENV
from lib.genai import SCHEMA_URL
from lib.ids import SequentialIds
from lib.tracing import make_provider
import asyncio, json, sys, tempfile
from pathlib import Path
from mcp import Client, StdioServerParameters
from opentelemetry import trace
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

HAND_WRITTEN = "00-" + "ab" * 16 + "-" + "cd" * 8 + "-01"  # a traceparent this app never made
CALLS = [("find_contact", {"user_id": "U0161", "name": "jake"}, {"traceparent": HAND_WRITTEN}), ("no_such_tool", {}, None)]
clock, exporter = VirtualClock("2026-12-08"), InMemorySpanExporter()
provider = make_provider("ambrewick-assistant", "1.0.0", "propagate-example", clock, SequentialIds(), exporter, SCHEMA_URL)
trace.set_tracer_provider(provider)  # the SDK injects its header only when a provider is configured


async def make_calls(params):
    """Make each call inside its own tool span, which is current while the call waits for its reply."""
    replies = []
    async with Client(params) as client:
        for number, (name, arguments, meta) in enumerate(CALLS):
            app = provider.get_tracer("ambrewick.assistant").start_span(f"execute_tool {name}", start_time=clock.at(number))
            with trace.use_span(app, end_on_exit=False):  # ended below, with a virtual end time
                replies.append((app, await client.call_tool(name, arguments, meta=meta)))
            app.end(end_time=clock.at(number + 1))
    return replies


with tempfile.TemporaryDirectory() as folder:
    spans_file = Path(folder) / "spans.jsonl"  # the server's spans; read once the server has exited
    params = StdioServerParameters(command=sys.executable, args=["-m", "lib.contacts_server"],
                                   cwd=str(Path(__file__).resolve().parent), env={SPANS_ENV: str(spans_file)})
    replies = asyncio.run(make_calls(params))
    server = [json.loads(line) for line in spans_file.read_text(encoding="utf-8").splitlines()]

(app, _), (_, unknown) = replies
client = next(s for s in exporter.get_finished_spans()  # the SDK's client span, child of the tool span
              if s.name.startswith("MCP send tools/call") and s.parent and s.parent.span_id == app.context.span_id)
span = next(r for r in server if r["parent_span_id"] == format(client.context.span_id, "016x"))
assert span["trace_id"] == format(app.context.trace_id, "032x") != "ab" * 16  # joined the app's trace, not the header's
assert unknown.is_error and unknown.content[0].text == "Unknown tool: no_such_tool"
print("find_contact, hand-written traceparent: server span joins the app's trace: yes")
print("find_contact, hand-written traceparent kept: no")
print("no_such_tool, reply is an error result: yes")
```

Output:

```text
find_contact, hand-written traceparent: server span joins the app's trace: yes
find_contact, hand-written traceparent kept: no
no_such_tool, reply is an error result: yes
```

With an OpenTelemetry tracer provider configured, the header in `_meta` is replaced before the request leaves the client. The server's span still joins the assistant's trace, and the header the code wrote does not survive, as the second printed line states. The third line shows how this server answers an unknown tool: with an [error](#how-a-span-records-failure) result, `isError` set, which the client hands back as a reply. The specification asks for a different reply, covered in [A timeout is raised, not returned](#errors-across-the-boundary). The yes lines rest on asserts, so the example stops if the server's span joins the header's trace instead.

The specification's 2026-07-28 revision reserves three `_meta` keys for trace context, `traceparent`, `tracestate` and `baggage`, and requires the W3C formats for their values. The proposal behind that reservation, SEP-414, came before the revision. The [GenAI conventions' MCP page](https://raw.githubusercontent.com/open-telemetry/semantic-conventions-genai/v0.1.0/docs/gen-ai/mcp.md) says that an instrumentation should inject through the configured propagators, and write the three keys without a prefix. That page links the earlier 2025-11-25 revision, so the two pages name different revisions, and we follow the later one.

**Working rule:** With an OpenTelemetry tracer provider configured, let the MCP SDK write `traceparent`, and never put `traceparent`, `tracestate` or `baggage` into `_meta` by hand. The SDK replaces a hand-written `traceparent`, but a hand-written `tracestate` or `baggage` survives beside the SDK's, so the server reads a value the SDK did not make. Write the header yourself only in code that runs without the SDK, and there the server reads it as written.

## The server span joins the trace {#joining-the-trace}

With the header written by the MCP SDK, as [The MCP SDK writes traceparent into _meta](#traceparent-in-meta) showed, the server's span lands under the right parent. Replaying message 16297 with the live server shows the parent links from the assistant's tool span down to the server's own lookup.

Example `server-span-joins` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Replay baseline day 1's message 16297 with the real contacts server over stdio, and check that the server's span joins
the assistant's trace under the SDK's client span. The prose's counts rest on the two count lines; the server's clock is
its own, so only counts are printed."""
from lib.assistant import RELEASES, Assistant
from lib.bm25 import Retriever
from lib.case import load_articles, load_messages, load_tool_durations
from lib.clock import VirtualClock
from lib.genai import SCHEMA_URL
from lib.ids import SequentialIds
from lib.replay import Replay
from lib.tools import LiveContacts, Tools
from lib.tracing import make_provider
import json, tempfile
from pathlib import Path
from opentelemetry import trace
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

DAY, RELEASE = "2026-12-08", RELEASES["r0"]  # baseline day 1, and the release its recording was made with
exporter = InMemorySpanExporter()
provider = make_provider("ambrewick-assistant", RELEASE.service_version, "baseline-day-1-replay", VirtualClock(DAY),
                         SequentialIds(), exporter, SCHEMA_URL)
trace.set_tracer_provider(provider)  # the SDK makes its client span with the global provider, so it must be this one

message = next(m for m in load_messages(DAY) if m.message_id == "16297")
clock = VirtualClock(DAY, start_ns=message.arrival_ns)  # the message's clock starts at its arrival
with tempfile.TemporaryDirectory() as folder:
    spans_file = Path(folder) / "contacts-spans.jsonl"  # the server writes here; it is read once the server has exited
    contacts = LiveContacts(clock, spans_file)
    outcome = Assistant(Replay(Path(__file__).resolve().parent / "data" / "recorded" / "baseline-day-1"), Retriever(load_articles(), RELEASE.top_k),
                        Tools(load_tool_durations(), contacts), clock, provider.get_tracer("ambrewick.assistant"), RELEASE).handle(message)
    contacts.close()
    server = [json.loads(line) for line in spans_file.read_text(encoding="utf-8").splitlines()]

mine = exporter.get_finished_spans()
app = next(s for s in mine if s.name == "execute_tool find_contact")
client = next(s for s in mine if s.name == "MCP send tools/call find_contact")
call = next(r for r in server if r["name"] == "tools/call find_contact")
lookup = next(r for r in server if r["name"] == "contacts.lookup")
trace_id = format(app.context.trace_id, "032x")
assert client.parent.span_id == app.context.span_id and call["trace_id"] == trace_id  # tool span, client span, same trace
assert call["parent_span_id"] == format(client.context.span_id, "016x")  # the server's span is under the client span
assert lookup["parent_span_id"] == call["span_id"] and lookup["trace_id"] == trace_id  # and its lookup under that

print("route chosen:", outcome.route)
print("spans in the message's trace, assistant:", sum(s.context.trace_id == app.context.trace_id for s in mine))
print("spans in the message's trace, contacts server:", sum(r["trace_id"] == trace_id for r in server))
print("contacts server span under the SDK's client span, in the same trace: yes")
```

Output:

```text
route chosen: messages
spans in the message's trace, assistant: 8
spans in the message's trace, contacts server: 3
contacts server span under the SDK's client span, in the same trace: yes
```

The chain has four spans and three links. The assistant's `execute_tool find_contact` span is the parent of `MCP send tools/call find_contact`, which the SDK makes as a CLIENT span for the request it sends. That client span is the parent of `tools/call find_contact` on the server, a SERVER span, and the server's `contacts.lookup` is the child of that. All four share one trace ID. The assistant holds 8 spans of the message's trace, and the server writes 3 more, in the same trace.

The client span is the one the assistant does not write. Its name, `MCP send tools/call find_contact`, does not follow the pattern the GenAI conventions' MCP page gives for spans, `{mcp.method.name} {target}`. We keep the MCP SDK's name, as chapter 3 keeps the names its package emits, because a span's name should match the code that made it.

The figure draws the same trace as a tree. Dots are the assistant's spans and squares are the server's, and a dashed line marks each parent link that crosses from one process to the other. The layout puts each span by its depth, not its time, because the server's clock is its own, and no time in this chapter comes from a server span: the figure and the output carry structure and parent links only.

Example `figure-cross-process-tree` (Python 3.13.16 · bm25s 0.3.16 · matplotlib 3.11.2 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Draw baseline day 1's message 16297 as one trace across the assistant and the contacts server, replayed with the live
server. The parent-links line rests on the printed count: two server spans have an SDK client span in the assistant as
their parent. Spans sit by depth, not time, since the server's clock is its own, so the figure shows structure only."""
from lib.dayrun import run_day_traced
from lib.figures import ACCENT, INK, MUTED, new_figure, save

traced = run_day_traced("2026-12-08", ["16297"])  # baseline day 1, with the live contacts server
# One row per span of the trace, from both processes. Span IDs link the rows and are never printed.
rows = [dict(r, process="assistant") for r in traced.spans] + [dict(r, process="contacts server") for r in traced.server]
trace_id = next(r["trace_id"] for r in rows if r["name"] == "execute_tool find_contact")
rows = [dict(r, id=r["span_id"], parent=r["parent_span_id"]) for r in rows if r["trace_id"] == trace_id]
by_id = {r["id"]: r for r in rows}
order = []  # depth-first: a span sits just below its parent, and its depth is its indent in the figure


def walk(row, depth):
    row.update(y=len(order), x=depth)
    order.append(row)
    for child in (r for r in rows if r["parent"] == row["id"]):
        walk(child, depth + 1)


for root in (r for r in rows if r["parent"] not in by_id):
    walk(root, 0)

fig, ax = new_figure(height=3.6, sharex=False)
for row in order:
    parent = by_id.get(row["parent"])
    if parent:  # an elbow from the parent's row down, then across; dashed where the link crosses the boundary
        cross = parent["process"] != row["process"]
        ax.plot([parent["x"], parent["x"], row["x"]], [parent["y"], row["y"], row["y"]], linewidth=1.2, zorder=1,
                color=ACCENT if cross else MUTED, linestyle="--" if cross else "-")
    server_row = row["process"] == "contacts server"  # squares for the server, dots for the assistant: shape, not colour alone
    ax.scatter(row["x"], row["y"], s=30, zorder=3, marker="s" if server_row else "o", color=ACCENT if server_row else INK)
    ax.text(row["x"] + 0.14, row["y"], f"{row['name']} ({row['process']})", va="center", fontsize=8, color=INK)
ax.invert_yaxis()
ax.set_xlim(-0.3, 6.4)
ax.axis("off")

cross = [r for r in rows if r["parent"] in by_id and by_id[r["parent"]]["process"] != r["process"]]
print("spans in the message's trace, assistant:", sum(r["process"] == "assistant" for r in rows))
print("spans in the message's trace, contacts server:", sum(r["process"] == "contacts server" for r in rows))
print("parent links across the boundary:", len(cross))
for r in cross:  # the SDK's client span is the parent; the server's span is the child
    print(f"{r['name']} in the contacts server, parent in the assistant:", by_id[r["parent"]]["name"])
assert sorted(r["name"] for r in cross) == ["tools/call find_contact", "tools/list"]  # the two links, and no other
save(fig, "cross-process-tree")
```

Output:

```text
spans in the message's trace, assistant: 8
spans in the message's trace, contacts server: 3
parent links across the boundary: 2
tools/call find_contact in the contacts server, parent in the assistant: MCP send tools/call find_contact
tools/list in the contacts server, parent in the assistant: MCP send tools/list
figure: figures/cross-process-tree.svg
```

*Figure 4.1. The spans of message 16297 as one trace, by depth; dashed links cross between the two processes.*

![One trace drawn as an indented tree: the assistant's spans, as dots, lead down to `execute_tool find_contact`, whose two SDK client spans each have one contacts-server span, as a square, joined by a dashed link; the server's `contacts.lookup` sits under its `tools/call` span](https://rollingedition.ai/books/observability-for-llm-applications/2026.11.2/figures/cross-process-tree.svg)

Figure 4.1 has two dashed links, and the printed count agrees: 2. One is the server's `tools/call find_contact`, whose parent is the client span for the lookup. The other is the server's `tools/list`, whose parent is the client span for the request the SDK sends for the server's tool list. The MCP SDK lists a server's tools after the first successful reply from a tool it has not listed yet, so that it can check the reply against the tool's output schema (`src/mcp/client/session.py`, `call_tool` and `validate_tool_result`, at mcp 2.3.0). This message's lookup succeeded, which is why it has that second link.

**Working rule:** After any call that crosses a process, check that each server span names a client span from the caller's trace as its parent, and count the links that cross. A link count of zero on a call you expected to cross means the header did not reach the server, so look at the request before you look at the server.

## Context is lost at a thread boundary {#lost-context}

The join works because the SDK's call runs in the same context as the tool span that made it. Python keeps the current span in a `ContextVar`, and each thread and each asyncio task has its own value of it. Three common ways of moving work lose that value: `threading.Thread(target=...)`, `executor.submit` and `loop.run_in_executor` each start the function with an empty context, so a span made there finds no parent. `asyncio.to_thread` and `asyncio.run_coroutine_threadsafe` copy the context, and that is why the book's `LiveContacts`, which sends each call to the client's thread with `run_coroutine_threadsafe`, keeps `find_contact`'s span in the message's trace.

A span that starts a trace of its own this way is a detached root: a span whose context was lost, so it starts a new trace and sits outside the message's trace. An orphan is a different failure. An orphan is a span whose parent ID names a span the store does not hold. It keeps the message's trace ID and stays in the message's trace. The two look different in the store. An orphan shows as a gap, a parent with no span behind it. A detached root looks like a healthy one-span trace, so nothing marks what it lost. [Spans by hand](#spans-by-hand) shows the other way a parent goes missing, when a process crashes partway through a message.

The example makes one span on each of four workers, all started inside one tool span, and shows which of them find its context.

Example `orphan-span-demo` (Python 3.13.16 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0), passing in Edition 2026.11.2:

```python
"""Make one span on each of four workers started inside one tool span, and show which ones find its context: a plain pool
thread, the same thread with carry(), an asyncio task, and the loop's executor. The prose's counts of detached roots rest
on the asserts, which compare each span's parent with the tool span."""
from lib.clock import VirtualClock
from lib.context import carry, new_task
from lib.genai import SCHEMA_URL
from lib.ids import SequentialIds
from lib.tracing import make_provider, span
from opentelemetry import trace
import asyncio
from concurrent.futures import ThreadPoolExecutor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

clock, exporter = VirtualClock("2026-12-08"), InMemorySpanExporter()
provider = make_provider("ambrewick-assistant", "1.0.0", "orphan-example", clock, SequentialIds(), exporter, SCHEMA_URL)
tracer = provider.get_tracer("ambrewick.assistant")


def retrieve(name):
    """The worker's work: one span, made on whichever thread runs this. Its times are fixed, as every span's are."""
    span(tracer, f"retrieve {name}", clock.at(1), clock.at(2))  # no parent given: the span takes the current one


async def from_task():
    retrieve("task")  # runs in its own task, which asyncio gave a copy of the tool span's context


async def main():
    """Runs as a task inside the tool span, starts a second task, and hands one worker to the loop's executor."""
    await new_task(from_task())
    await asyncio.get_running_loop().run_in_executor(None, retrieve, "executor")  # copies no context


app = tracer.start_span("execute_tool retrieve", start_time=clock.at(0))
with trace.use_span(app, end_on_exit=False):  # current while the workers run, so their spans can find it
    with ThreadPoolExecutor(max_workers=1) as pool:
        pool.submit(retrieve, "plain").result()  # the pool's thread starts with an empty context
        pool.submit(carry(retrieve), "carried").result()  # carry() runs the work in a copy of this context
    asyncio.run(main())
app.end(end_time=clock.at(3))

spans = {s.name: s for s in exporter.get_finished_spans()}
joined = {name: spans[name].parent is not None and spans[name].parent.span_id == app.context.span_id for name in spans}
assert joined == {"retrieve plain": False, "retrieve carried": True, "retrieve task": True, "retrieve executor": False,
                  "execute_tool retrieve": False}
assert all(spans[n].context.trace_id != app.context.trace_id for n in ["retrieve plain", "retrieve executor"])  # own traces
print("retrieve on a plain thread, joins the tool span: no")
print("retrieve on a thread with carry(), joins the tool span: yes")
print("retrieve in an asyncio task, joins the tool span: yes")
print("retrieve through run_in_executor, joins the tool span: no")
print("detached roots without the helper:", sum(not joined[n] for n in ["retrieve plain", "retrieve executor"]))
print("detached roots with the helper:", sum(not joined[n] for n in ["retrieve carried"]))
print("detached root's trace differs from the tool span's: yes")
```

Output:

```text
retrieve on a plain thread, joins the tool span: no
retrieve on a thread with carry(), joins the tool span: yes
retrieve in an asyncio task, joins the tool span: yes
retrieve through run_in_executor, joins the tool span: no
detached roots without the helper: 2
detached roots with the helper: 0
detached root's trace differs from the tool span's: yes
```

The plain thread's span is a detached root, and the first printed line says it did not join the tool span. The wrapped thread's span joins, and so does the task's, because asyncio gives a task a copy of the context that was current when the task was made. The executor worker loses the context like the plain thread, so its span is a detached root too. The counts make the [cost](#cost-per-route) plain: 2 detached roots without the helper, and 0 with it. The last line states that a detached root's trace differs from the tool span's, which is the test for one: a trace ID other than the one its work belongs to.

The fix is `carry()`, from the book's shared module `lib/context.py`, which wraps a function so it runs in a copy of the caller's context. `new_task()` starts an asyncio task with an explicit copy of the context. asyncio copies it anyway, and the helper makes the copy visible in code. Two standard alternatives exist. `opentelemetry-instrumentation-threading` patches `Thread` and `ThreadPoolExecutor` so they carry the context, and `asyncio.to_thread` copies it for the work it starts. We recommend `carry()` in code the team owns, because the copy is visible at the call site and nothing is patched. The instrumentation is for libraries whose own thread pools the team cannot change.

**Working rule:** Wrap every function that a thread, a thread pool or `run_in_executor` runs in `carry()`, and start asyncio tasks with `new_task()`, so each one starts from a copy of the caller's context. A span that finds no parent raises no error and changes no status, so the context has to be carried at every hand-off.

## What goes in baggage {#what-goes-in-baggage}

A trace ID and a parent ID say where a span belongs, and a server often needs one more value to label its own spans: which release and which [prompt version](#release-markers-in-the-spans) made the call. Baggage is the mechanism for that. The standard for it is the [W3C Baggage specification](https://www.w3.org/TR/2024/CR-baggage-20240530/), a Candidate Recommendation Snapshot of 30 May 2024. It is not yet a Recommendation, and we cite it at that status.

Baggage is a set of key-value pairs that travels with the context into every later process when every process along the way propagates it. The specification warns that baggage may carry sensitive information, advises that no proprietary or confidential information goes in it, and says that its keys and values can be passed on to other systems. Those warnings decide what we put there. Only the release and the prompt version go in, under the keys `ambrewick.release` and `ambrewick.prompt.version`. A release has the form `MAJOR.MINOR.PATCH` in digits, and a prompt version is `p` followed by digits. Running the example below shows the allowed list, the keys a call carries, and the refusals.

Example `baggage-keys` (Python 3.13.16 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0), passing in Edition 2026.11.2:

```python
"""Put the release and the prompt version in baggage, and carry them as an MCP call would: the global propagator writes the
`baggage` entry that the SDK sends in `_meta`. A user identifier is refused under an unknown key and under an allowed one.
The prose rests on the last two printed lines, which the asserts back."""
from lib.context import ALLOWED_BAGGAGE_KEYS, baggage_context
from opentelemetry import baggage, propagate


def refused(values):
    """True when baggage_context refuses these values."""
    try:
        baggage_context(values)
    except ValueError:
        return True
    return False


ctx = baggage_context({"ambrewick.release": "1.0.0", "ambrewick.prompt.version": "p1"})
carrier = {}
propagate.inject(carrier, context=ctx)  # the same global propagator the SDK uses for `_meta`
carried = sorted(baggage.get_all(ctx))
assert carried == sorted(ALLOWED_BAGGAGE_KEYS)  # nothing else is carried
assert carrier["baggage"] == "ambrewick.prompt.version=p1,ambrewick.release=1.0.0"
assert refused({"ambrewick.user.id": "U0161"})  # a key that is not allowed
assert refused({"ambrewick.release": "U0161"})  # a user identifier under an allowed key, which is not in its form

print("allowed baggage keys:", ", ".join(sorted(ALLOWED_BAGGAGE_KEYS)))
print("baggage keys carried on a call:", ", ".join(carried))
print("baggage entry sent in _meta:", carrier["baggage"])
print("user identifier refused: yes")
print("user identifier under an allowed key refused: yes")
```

Output:

```text
allowed baggage keys: ambrewick.prompt.version, ambrewick.release
baggage keys carried on a call: ambrewick.prompt.version, ambrewick.release
baggage entry sent in _meta: ambrewick.prompt.version=p1,ambrewick.release=1.0.0
user identifier refused: yes
user identifier under an allowed key refused: yes
```

Only the two allowed keys leave the process: the propagator writes them into one `baggage` entry, and the SDK sends that entry in `_meta` beside `traceparent`. The helper refuses a key outside the allowed list, and a value outside its key's form, so a user identifier is refused even under an allowed key. The last two lines report those refusals.

`baggage_context` does not see two cases. It starts from the current context, so baggage that arrived from upstream passes through it unchecked, and a direct call to `opentelemetry.baggage.set_baggage` skips it altogether. We recommend that code calls `baggage_context` and never `set_baggage` directly.

A user identifier does not go into baggage, and we do not put one there in any form. The keyed pseudonym we use for users is in [Keyed user pseudonyms](#keyed-user-pseudonyms), where chapter 12 explains why it is safe to put in a span.

**Working rule:** Put a value in baggage only when a process downstream needs it to label its own spans, and only under a key on the allowed list. A value that identifies a person stays out, however short or harmless it looks in one message.

## A timeout is raised, not returned {#errors-across-the-boundary}

The lookup can fail in more than one way, and the failures arrive differently at the caller. A tool that the server does not have comes back as an error result from this server. A conforming server built by another team fails differently: the [specification's tools page](https://modelcontextprotocol.io/specification/2026-07-28/server/tools) makes an unknown tool a protocol error, a JSON-RPC error with code -32602, which the client raises as `MCPError`. A read timeout does not come back from any server at all. The SDK raises it as an `MCPError`, with the code -32001.

The specification assigns no code to errors that are purely local to an implementation, such as a request timeout raised inside an SDK. So -32001 is not an MCP code. The client made it itself, and no server sent it. The specification puts -32001 in its legacy range, -32000 to -32019, where new implementations should not use codes and receivers must not assume a meaning, and it asks that a local error never be mistaken for a peer's. mcp raises the timeout as the same `MCPError` class it uses for a server's errors, so a query over `ambrewick.mcp.error_code` must not count -32001 as the server's error. We call -32001 the SDK's code for a read timeout, and [chapter 8](#retries-under-a-timeout) reads these timeouts across the incident day under the same name.

This section uses an injected incident, `inc-contacts-timeout`, which makes the contacts server answer too slowly for a window of the incident day. The injection is labelled as one in the spans it touches, and the example's first printed line names it.

Example `contacts-timeout-live` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Replay incident-day message 16297 with the live contacts server, inside the injected timeout window. Each attempt of
find_contact is its own execute_tool span. The first raises MCPError with code -32001, the SDK's code for a read timeout,
which the MCP spec does not assign: that span ends ERROR, with error.type MCPError and an exception event. The retry starts
2.5 s later, times out too, and the tool step gives up."""
from lib.dayrun import run_day_traced
from lib.tools import TIMEOUT_CODE

traced = run_day_traced("2026-12-09", ["16297"])  # the incident day, with the live server inside its window
outcome = traced.runs[0].outcome
attempts = sorted((r for r in traced.spans if r["name"] == "execute_tool find_contact"),
                  key=lambda r: r["attributes"]["ambrewick.attempt"])
injected = [r for r in traced.server if r["name"] == "tools/call find_contact" and "ambrewick.incident.id" in r["attributes"]]
first, second = attempts
assert len(attempts) == 2 and outcome.source == "model"  # the retry times out too, and the answer comes from the model
assert all(a["status"] == "ERROR" and a["attributes"]["error.type"] == "MCPError" for a in attempts)
assert first["attributes"]["ambrewick.mcp.error_code"] == TIMEOUT_CODE
assert len(injected) == 2 and all(r["attributes"]["ambrewick.incident.injected"] is True for r in injected)
print("injected incident, ID:", injected[0]["attributes"]["ambrewick.incident.id"])
print("attempts of find_contact:", len(attempts))
print("attempt 1, status and error.type:", first["status"], first["attributes"]["error.type"])
print("attempt 1, error code:", first["attributes"]["ambrewick.mcp.error_code"])
print("attempt 1, exception event:", first["events"][0]["attributes"]["exception.type"].rsplit(".", 1)[-1])
print("attempt 1, time:", f"{(first['end_ns'] - first['start_ns']) / 1e9:.1f} s")  # the 2.0 s timeout
print("attempt 2 starts after attempt 1:", f"{(second['start_ns'] - first['start_ns']) / 1e9:.1f} s")  # 2.0 s + 0.5 s
print("tool step, time:", f"{(second['end_ns'] - first['start_ns']) / 1e9:.1f} s")
```

Output:

```text
injected incident, ID: inc-contacts-timeout
attempts of find_contact: 2
attempt 1, status and error.type: ERROR MCPError
attempt 1, error code: -32001
attempt 1, exception event: MCPError
attempt 1, time: 2.0 s
attempt 2 starts after attempt 1: 2.5 s
tool step, time: 4.5 s
```

Message 16297 on the incident day runs with the live server inside the injected window. The first attempt times out, and the printed lines show its status, its [error type](#how-a-span-records-failure) and its code, which is -32001. The attempt takes 2.0 s on the virtual clock, which is the timeout the client is configured with. The second attempt starts 2.5 s after the first, also times out, and the tool step gives up after 4.5 s in all.

Each attempt is its own `execute_tool` span, and we count each one as its own operation. A failed attempt is therefore ERROR, with `error.type` set to the class the caller received, `MCPError`, not the inner `TimeoutError` that the SDK caught underneath it. The code goes on `ambrewick.mcp.error_code`, not on `rpc.status_code`: the conventions define that attribute as the error code from the JSON-RPC response, and a local timeout has no response. The retry does not turn the first attempt into a success. The conventions' [recording-errors page](https://raw.githubusercontent.com/open-telemetry/semantic-conventions/v1.45.0/docs/general/recording-errors.md) says that retried errors stay off the span, but that rule covers an operation that succeeds on retry, and here each attempt is one operation that failed. The alternative reading would hide the first attempt's timeout, and chapter 8 needs that timeout to count the failures a message met.

**Working rule:** Record each attempt of a call as its own span, with its own status and error type, and never let one error span stand for a call whose earlier attempts also failed. Read the error type from the exception the caller receives, and read the code from the error the client raises.

## What goes wrong in production {#across-processes-in-production}

The failures in this chapter raise no error. A hand-written header that the SDK replaces passes silently, and a server span with no parent is exported like any other span. Three queries find them, and each needs a place where the spans of both processes sit together, which chapter 5 provides. One counts the cross-process links: the parent links that cross from one process to the other. One counts detached roots: root spans other than the agent span `invoke_agent ambrewick-assistant`, in either process, and a server span that arrived with no `traceparent` is one too. The last counts orphans: spans whose parent ID names no stored span. Without the queries, nothing in the process fails, so the counts are the only signal.

Two more things go wrong in production. Libraries that run work on their own thread pools lose the context unless they were written to copy it, and a team's `carry()` cannot reach a pool it does not own, so a span that looks like it belongs to a message can start a trace of its own. Baggage goes wherever the request goes, to every process the call reaches, so a value that was harmless in one process can become a leak in the next. The helper checks only what the book sends. Baggage that arrives from upstream passes through unchecked, which is the limit [What goes in baggage](#what-goes-in-baggage) describes.

The trace's two halves now sit in two places, the assistant's spans in its memory and the server's in its file, and [The book's receiver](#the-book-receiver) is where chapter 5 puts them together.

**Working rule:** Run the cross-process link count and the detached-root and orphan counts after any change to tool or worker code, and on every release. Treat a change in any of them as a broken join until someone has explained it.

## The decisions this chapter made {#across-processes-decisions}

Each decision below is a judgement we could be wrong about, so each gives its reason and the example that checks it.

- We let the MCP SDK write `traceparent` whenever a tracer provider is configured, and we keep hand-written trace keys out of `_meta`. The header the server reads is the one the SDK writes, so a second copy in the code would never reach the server. `propagate-into-the-tool` checks it, where the hand-written header is replaced.
- We treat each server process as one run and read its span file once the process has exited. A run starts and ends as one unit, and the file holds every span only after the process has finished writing. `server-span-joins` checks the join, and `server-span-without-context` shows the recording where it is missing.
- We carry the context into every thread, pool and asyncio task that makes spans, with `carry()` and `new_task()`. A detached root raises nothing, so the context has to be carried at every hand-off. `orphan-span-demo` checks it, where the plain thread's span and the executor's are the detached roots.
- We put only the release and the prompt version in baggage, and we refuse every other key and every value outside its form. Baggage travels to every process a call reaches, and the specification warns about what it may carry. `baggage-keys` checks it, where a user identifier is refused under an unknown key and under an allowed one.
- We record each attempt of a tool call as its own span, and we name -32001 as the SDK's code, not an MCP code. Chapter 8 counts the failures a message met, and the first attempt's timeout is one of them, so one span for the whole call would hide it. `contacts-timeout-live` shows both attempts as ERROR spans.

# Send traces to a backend you can run

By the end of this chapter you can send the spans of both processes to one receiver that you run on one machine, check that it stores the rows the exporter sent, query those rows with SQL, and say what each named backend accepts and what its page does not say. Chapter 4 ended with one message to Ambrewick, split across two places. The assistant's spans sit in its memory, and the contacts server writes its spans to a file that the assistant reads only after the server has exited. Neither place can answer a question about the whole message, and both teams need one place to query them that they can change next year.

Every count in this chapter is printed by an example from a recorded run. The few other numbers come from a probe or a cited page, and the text says which. So this chapter builds one receiver for both processes, checks its rows against the exporter's, and puts MLflow on disk beside it.

## The exporter sends each span over OTLP {#otlp-over-http}

Chapter 1 said that an exporter sends each ended span "to memory, a file or an OTLP endpoint", and left the endpoint for this chapter. OTLP is OpenTelemetry's protocol for sending telemetry to a receiver. A backend stores spans and answers queries over them. A collector is a separate process that receives, processes and exports telemetry, and it is taken up in [Changing the backend](#changing-backends). The protocol itself is written down in the [OTLP specification](https://opentelemetry.io/docs/specs/otlp/), which the docs site gives at version 1.11.1, and we cite it for the path, the content types and the status codes.

For traces, the request goes to the path `/v1/traces`, and its body is either Protocol Buffers, sent as `application/x-protobuf`, or JSON, sent as `application/json`. A successful export gets HTTP 200. The specification says a client should [retry](#retries-under-a-timeout) a request that gets 429, 502, 503 or 504, and must not retry any other 4xx or 5xx code. The Python exporter, `OTLPSpanExporter` in `opentelemetry-exporter-otlp-proto-http` at 1.45.2, follows the same four codes in its source, and it also retries connection failures. It makes up to six attempts with backoff, and a `Retry-After` header replaces the backoff. The whole export, retries included, stops at the exporter's timeout. That timeout is 10 seconds by default (`DEFAULT_TIMEOUT`), and at the default a closed port gets four attempts, not six; six needs a longer timeout. When the last attempt fails, the exporter returns the batch as failed, and the batch is dropped and logged, not kept for later.

Here a dev-day message's three spans go through that exporter to a receiver on loopback, which the next section describes: its agent span, its chat span and its `execute_tool find_contact` span, whose counts come from the recording. Two things about a synchronous processor, the kind the examples use, are checked along the way.

Example `otlp-export-loopback` (Python 3.13.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Export one dev-day message's three spans over OTLP/HTTP to the book's receiver on loopback, and check that a span's
request is in the receiver when its span.end() returns. The stored rows equal the in-memory exporter's rows, so the
protobuf round trip loses nothing the book's rows keep; the request count is printed and the yes lines are asserted."""
from lib.assistant import AGENT, RELEASES
from lib.clock import VirtualClock
from lib.export import spans_to_rows
from lib.genai import SCHEMA_URL
from lib.ids import SequentialIds
from lib.otlp import message_spans, start
from lib.tracing import make_provider
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

DAY, RELEASE = "2026-12-07", RELEASES["r0"]
receiver = start()                       # the book's receiver on loopback; the port is never printed
memory = InMemorySpanExporter()          # the same spans, kept in memory, to compare with what arrives
clock = VirtualClock(DAY)
provider = make_provider(AGENT, RELEASE.service_version, "otlp-export-loopback", clock, SequentialIds(), memory, SCHEMA_URL)
# SimpleSpanProcessor calls the exporter when each span ends, so the request is sent on the ending thread (O-7)
provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint=receiver.endpoint)))
root, chat, tool = message_spans(provider.get_tracer("ambrewick.assistant"), clock)

assert receiver.address == "127.0.0.1"   # bound to loopback only, never to a network address
assert len(receiver.requests()) == 3     # one request per span the processor exported
assert sum(count == 1 for _, count in receiver.requests()) == 3  # each request holds one span
assert receiver.rows() == spans_to_rows(memory)  # the stored rows equal the exporter's own rows

# A span from a provider with only the OTLP exporter: its request must be in the receiver when end() returns.
probe = TracerProvider(resource=Resource.create({"service.name": AGENT, "service.instance.id": "probe"}))
probe.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint=receiver.endpoint)))
before = len(receiver.requests())
# 36001 s is an offset on the virtual clock, past the message's spans, so the probe's times do not overlap them
probe.get_tracer("probe").start_span("probe", start_time=clock.at(36001)).end(end_time=clock.at("36001.1"))
assert len(receiver.requests()) == before + 1

print("bound to loopback: yes (asserted)")
print("requests for the message's three spans:", before)
print("spans per request: one in each, for every request (asserted)")
print("content types of the requests:", ", ".join(sorted({kind for kind, _ in receiver.requests()})))
print("stored rows equal the exporter's rows: yes (asserted)")
print("a request is in the receiver when span.end() returns: yes (asserted)")
receiver.stop()
```

Output:

```text
bound to loopback: yes (asserted)
requests for the message's three spans: 3
spans per request: one in each, for every request (asserted)
content types of the requests: application/x-protobuf
stored rows equal the exporter's rows: yes (asserted)
a request is in the receiver when span.end() returns: yes (asserted)
```

The receiver logged 3 requests for the message's three spans, and each request's body was application/x-protobuf. Each of the three spans reached the receiver in a request of its own, and each request was there before its `span.end()` returned, because `SimpleSpanProcessor` calls the exporter on the thread that ends the span. Chapter 1 chose that processor so that every printed span has been exported by the time it is printed. The example asserts these lines, so it stops if one of them is false. The rows the receiver stored equal the rows the exporter built in memory, so the protobuf round trip loses nothing the book's rows keep. The compared rows leave out the status description, links, trace state, flags, scope version, schema URL and the `telemetry.sdk.*` resource values.

The synchronous processor has a [cost](#cost-per-route), and a probe shows it. A probe pointed the exporter at a closed loopback port, at its default 10-second timeout; `span.end()` returned after about 7 seconds, after four attempts, and no exception reached the application.

**Working rule:** Give each process the endpoint of its receiver, and send production spans with the batch processor that chapter 1 recommends, so the request is not made on the thread that ends the span. In production we recommend that processor, because its export runs on its own schedule and not on the thread that ends a span. The trade is the one chapter 1 named: spans still in its queue are lost if the process dies.

## The book's receiver holds both processes' spans {#the-book-receiver}

The receiver is the book's own: an HTTP server from the standard library that decodes requests with OpenTelemetry's protobuf classes, started on loopback by `start()` in the book's `lib/otlp.py`. It decodes a request in either encoding, Protocol Buffers or JSON, and stores each span as a row in the shape the book's export writes to JSON lines. It stores the request before it replies, which is what [the last section's assertion](#otlp-over-http) relied on. It keeps the rows in memory, for one run. That makes it a test receiver for this book, not a store a team would keep for a year. The next section's backend keeps its rows on disk.

Both processes export to it. The assistant's exporter runs in the assistant's own process. The contacts server gets the endpoint from its environment: when `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` or `OTEL_EXPORTER_OTLP_ENDPOINT` names one, the server exports its spans over OTLP itself. When neither is set, it writes the JSON-lines file that [The contacts server is another process](#the-contacts-server) describes. The receiver takes a port that the system chooses, and the examples never print it; the contacts server is still a stdio subprocess and only sends to that port.

Example `two-processes-one-receiver` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Replay baseline day 1's messages that route to the messages tools, with the contacts server live, and send both
processes' spans to one receiver: every server span joins a trace the assistant made. The server's clock is its own,
so the example prints counts only, never a span time from it."""
from lib.assistant import AGENT
from lib.case import load_messages, scenario_to_route
from lib.contacts_server import SERVICE_NAME
from lib.dayrun import run_day_traced
from lib.otlp import start

DAY = "2026-12-08"
receiver = start()                   # the book's receiver on loopback; its port is never printed
ids = {m.message_id for m in load_messages(DAY) if scenario_to_route(m.scenario) == "messages"}  # only these can call a contacts tool
traced = run_day_traced(DAY, message_ids=ids, otlp_endpoint=receiver.endpoint)  # both processes export here
stored = receiver.rows()
mine = [row for row in stored if row["resource"]["service.name"] == AGENT]
theirs = [row for row in stored if row["resource"]["service.name"] == SERVICE_NAME]
mine_ids = {row["span_id"] for row in mine}
find = {row["trace_id"] for row in mine if row["name"] == "execute_tool find_contact"}  # those messages' traces
both = {row["trace_id"] for row in mine} & {row["trace_id"] for row in theirs}

assert mine == traced.spans                    # the stored assistant rows equal export.py's rows
assert find <= {row["trace_id"] for row in theirs}  # each find_contact message has server spans in its trace
assert find <= {row["trace_id"] for row in mine if row["name"].startswith("invoke_agent")}  # and a message root
# every server span whose parent is set names a stored span, from either process: the join crosses no gap
assert all(row["parent_span_id"] in mine_ids | {r["span_id"] for r in theirs} for row in theirs if row["parent_span_id"])

rooted = {row["trace_id"] for row in mine if row["name"].startswith("invoke_agent")}
print("messages replayed:", len(traced.runs))
print("messages that called find_contact:", len(find))
print("assistant traces with a message root:", len(rooted))
print("assistant traces without one (the startup, with its discovery call):", len({row["trace_id"] for row in mine} - rooted))
print("traces with spans from both processes:", len(both))
print("spans from the assistant, in the find_contact messages:", sum(row["trace_id"] in find for row in mine))
print("spans from the contacts server, in the find_contact messages:", sum(row["trace_id"] in find for row in theirs))
print("spans from the assistant, all messages:", len(mine))
print("spans from the contacts server, all messages:", len(theirs))
print("contacts server spans under an assistant span:", sum(row["parent_span_id"] in mine_ids for row in theirs))
print("stored assistant rows equal the exporter's rows: yes (asserted)")
receiver.stop()
```

Output:

```text
messages replayed: 17
messages that called find_contact: 3
assistant traces with a message root: 17
assistant traces without one (the startup, with its discovery call): 1
traces with spans from both processes: 4
spans from the assistant, in the find_contact messages: 22
spans from the contacts server, in the find_contact messages: 7
spans from the assistant, all messages: 70
spans from the contacts server, all messages: 8
contacts server spans under an assistant span: 5
stored assistant rows equal the exporter's rows: yes (asserted)
```

The replay runs the messages from [baseline day 1](#the-contacts-server) that take the `messages` route, which goes to the messages tools: 17 in all, and 3 of them call `find_contact`. The receiver stores the spans of both processes, and the output counts each side. The server's spans sit in the trace of each message that asked for a contact. Of all the traces, 4 hold spans from both processes: the three lookups and the startup.

One trace in the replay answers no message, and that is by design: the contacts server starts once, inside a `contacts startup` span, so its discovery call is a trace of its own. It is the one root expected besides the message roots. A server started outside any span would make its `server/discover` call a [detached root](#lost-context) of its own, and one started per message would make one for every message. This replay follows [chapter 4's one process per run](#the-contacts-server), where a run is the server's whole life, here one replay. The output shows it: 1 assistant trace has no message root, and it is the startup. Every message has its own root, 17 in all, and each lookup joins its message's trace.

The rows the receiver stored equal the rows that `lib/export.py` writes for the same spans. That is the claim the rest of the book depends on. From here on, the book's queries read rows of this shape, and chapter 8 runs its failure queries on the receiver itself, so this check shows that those rows are what a backend would hold, not a copy the book made for its own queries.

The rows checked above are what the queries read, and the example writes them to a JSON Lines file first. `connect()` in `lib/query.py` opens an in-memory DuckDB connection, at 2.0.1, with one view named `spans` over that file.

Example `query-stored-spans` (Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Query the receiver's stored rows with DuckDB: the spans each process stored, the join across the process boundary,
and the orphans (spans whose parent names no stored span). Every query orders by its group keys, so the printed order
is the same on every run; the server's own times are never printed."""
import tempfile
from pathlib import Path

from lib.case import load_messages, scenario_to_route
from lib.contacts_server import SERVICE_NAME
from lib.dayrun import run_day_traced
from lib.export import write_jsonl
from lib.otlp import start
from lib.query import connect

DAY = "2026-12-08"
receiver = start()                   # the book's receiver on loopback, as in the example before
ids = {m.message_id for m in load_messages(DAY) if scenario_to_route(m.scenario) == "messages"}
run_day_traced(DAY, message_ids=ids, otlp_endpoint=receiver.endpoint)  # both processes export to the receiver
with tempfile.TemporaryDirectory() as folder:
    rows_file = Path(folder) / "spans.jsonl"          # the stored rows, as a file a query can read
    write_jsonl(rows_file, receiver.rows())
    db = connect(rows_file)
    assert db.execute("SELECT count(*) FROM spans").fetchone()[0] == len(receiver.rows())
    per_service = db.execute("SELECT service, count(*), count(DISTINCT trace_id) FROM spans GROUP BY service "
                             "ORDER BY service").fetchall()
    server_names = db.execute("SELECT name, count(*) FROM spans WHERE service = ? GROUP BY name ORDER BY name",
                              [SERVICE_NAME]).fetchall()
    # a server span whose parent is an assistant span: the join across the process boundary
    joins = db.execute("SELECT c.name, count(*) FROM spans c JOIN spans p ON c.parent_span_id = p.span_id "
                       "WHERE c.service <> p.service GROUP BY c.name ORDER BY c.name").fetchall()
    both = db.execute("SELECT count(*) FROM (SELECT trace_id FROM spans GROUP BY trace_id "
                      "HAVING count(DISTINCT service) = 2 ORDER BY trace_id)").fetchone()[0]
    orphans = db.execute("SELECT count(*) FROM spans c WHERE c.parent_span_id IS NOT NULL AND NOT EXISTS "
                         "(SELECT 1 FROM spans p WHERE p.span_id = c.parent_span_id) ORDER BY 1").fetchone()[0]

for service, count, traces in per_service:
    print(f"stored spans from {service}: {count}, in {traces} traces")
for name, count in server_names:
    print(f"contacts server spans named {name}: {count}")
for name, count in joins:
    print(f"contacts server spans under an assistant span, named {name}: {count}")
print("traces holding both processes' spans:", both)
print("orphans in the stored rows:", orphans)
```

Output:

```text
stored spans from ambrewick-assistant: 70, in 18 traces
stored spans from contacts-server: 8, in 4 traces
contacts server spans named contacts.lookup: 3
contacts server spans named server/discover: 1
contacts server spans named tools/call find_contact: 3
contacts server spans named tools/list: 1
contacts server spans under an assistant span, named server/discover: 1
contacts server spans under an assistant span, named tools/call find_contact: 3
contacts server spans under an assistant span, named tools/list: 1
traces holding both processes' spans: 4
orphans in the stored rows: 0
```

The first two lines count the stored spans by process, the assistant's and the contacts server's. The join is the query that matters. A contacts server span whose parent is an assistant span crossed the process boundary and joined. Three names do that: `tools/call find_contact`, with 3 spans; `server/discover`, the startup's discovery, with 1; and `tools/list`, the tool listing, with 1. The lookup's own span, `contacts.lookup`, is not in that list, because its parent is the server's `tools/call` span. The join is one hop, at the server's entry point.

The last two lines are the checks that the halves joined. 4 traces hold spans from both processes, and 0 orphans are stored. The term is defined in [Context is lost at a thread boundary](#lost-context), and a zero there means every stored parent link resolves. A `GROUP BY` or a join has no defined order in DuckDB, whatever the setting, and DuckDB's [order-preservation page](https://duckdb.org/docs/2.0/sql/dialect/order_preservation) at version 2.0 lists both. So every query in the example orders its rows. A probe at this version, with the setting off, saw a query with no `ORDER BY` return its rows in a different order on another run.

**Working rule:** Send every process's spans to one receiver, and check the join, the detached roots and the orphan count before you read a query over one process. Leave the `contacts startup` span out of the detached-root count by its name. If no server span sits under an assistant span, or any orphan is stored, the halves did not join or a span was lost, and the other queries cannot yet be trusted. For a team, we recommend one receiver for every process, because a trace split over two stores cannot be read whole; the trade is one more place to run and keep.

## MLflow on SQLite takes the same spans {#mlflow-on-sqlite}

The receiver keeps rows in memory. A team needs a backend that stores them on disk and answers queries over them. MLflow 3.18.0 is one the book can run. Its [OpenTelemetry ingest page](https://mlflow.org/docs/3.18.0/genai/tracing/opentelemetry/ingest/) says that OTLP ingest starts at 3.6.0, takes OTLP over HTTP only, with no gRPC, and needs a SQL-based backend store, which the book provides as SQLite. The route at this version declares the `x-mlflow-experiment-id` header as required, in its source (`mlflow/server/otel_api.py`). A probe found that without the header the route answers 422, a code the exporter does not retry, so the batch is dropped. The book's exporter always sends the header.

The book starts the server on loopback with a SQLite file in a temporary folder. It turns telemetry off through environment variables. It stops the server by its process group, since the server starts worker processes of its own and signalling the parent alone leaves them running.

Example `mlflow-search-traces` (Python 3.13.16 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Send one message's three spans to MLflow 3.18.0 on SQLite over OTLP/HTTP, and read them back with search_traces. MLflow
returns span IDs base64-encoded, so the example decodes them before comparing. The code reads the trace's total token
usage from its metadata, and MLflow stores no cost, because it has no price for the model the chat span names."""
import tempfile

from lib.assistant import AGENT, RELEASES
from lib.clock import VirtualClock
from lib.export import spans_to_rows
from lib.genai import SCHEMA_URL
from lib.ids import SequentialIds
from lib.mlflow_server import otlp_exporter, running, stored_spans, trace_usage
from lib.otlp import message_spans
from lib.tracing import make_provider

import mlflow
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

DAY, RELEASE = "2026-12-07", RELEASES["r0"]
memory = InMemorySpanExporter()
clock = VirtualClock(DAY)
with tempfile.TemporaryDirectory() as folder, running(folder, "ambrewick-sample") as (uri, experiment):
    provider = make_provider(AGENT, RELEASE.service_version, "mlflow-search-traces", clock, SequentialIds(), memory,
                             SCHEMA_URL)
    provider.add_span_processor(SimpleSpanProcessor(otlp_exporter(uri, experiment)))
    message_spans(provider.get_tracer("ambrewick.assistant"), clock)
    found = mlflow.search_traces(locations=[experiment])

spans, usage = stored_spans(found), trace_usage(found)
root = next(span for span in spans if span["parent"] is None)
chat = next(span for span in spans if span["name"].startswith("chat "))
# the trace ID is "tr-" followed by the 32 hex digits of the OpenTelemetry trace ID, 35 characters in all
assert len(found) == 1 and len(found.iloc[0]["trace_id"]) == 35 and found.iloc[0]["trace_id"].startswith("tr-")
assert {span["span"] for span in spans} == {row["span_id"] for row in spans_to_rows(memory)}  # decoded IDs match
assert all(span["parent"] in (None, root["span"]) for span in spans)  # the chat and tool spans sit under the root
assert chat["attributes"]["mlflow.spanType"] == "CHAT_MODEL"  # MLflow's own label, added on the chat span
assert usage["total"] == usage["input"] + usage["output"]  # cache reads are not added again
# MLflow prices a span only when it knows the span's model, and this book's model is not in its table
assert "mlflow.llm.cost" not in chat["attributes"] and "mlflow.trace.cost" not in found.iloc[0]["trace_metadata"]

print("traces found for the experiment:", len(found))
print("spans in the trace:", len(spans))
print("span IDs, decoded from base64, equal the exporter's IDs: yes (asserted)")
print("chat span, MLflow span type:", chat["attributes"]["mlflow.spanType"])
print("chat span, model MLflow recorded:", chat["attributes"]["mlflow.llm.model"])
print("trace token usage, input:", usage["input"])
print("trace token usage, output:", usage["output"])
print("trace token usage, cache read:", usage["cache_read"])
print("trace token usage, total = input + output: yes (asserted)")
print("cost MLflow stored for this model, on the chat span and in the trace: none (asserted)")
```

Output:

```text
traces found for the experiment: 1
spans in the trace: 3
span IDs, decoded from base64, equal the exporter's IDs: yes (asserted)
chat span, MLflow span type: CHAT_MODEL
chat span, model MLflow recorded: qwen3-4b-instruct-2507
trace token usage, input: 331
trace token usage, output: 38
trace token usage, cache read: 192
trace token usage, total = input + output: yes (asserted)
cost MLflow stored for this model, on the chat span and in the trace: none (asserted)
```

MLflow hands back the same three spans, with their IDs in its own encodings. They are the dev-day message from [the exporter section](#otlp-over-http), and they come back through `search_traces(locations=...)`. MLflow returns 1 trace with 3 spans. Its trace ID is `tr-` followed by the 32 hexadecimal digits of the OpenTelemetry trace ID, and its span IDs come back base64-encoded. They are decoded before the check, which asserts that the decoded IDs equal the exporter's, so each span can be matched to its source. `experiment_ids` is deprecated in favour of `locations`, as `@deprecated_parameter("experiment_ids", "locations")` in `mlflow/tracing/fluent.py` shows, so the code passes `locations`. A probe saw a FutureWarning from the old argument.

MLflow marks the chat span with its own attribute, `mlflow.spanType`, and the marked value is CHAT_MODEL. MLflow keeps the span's `gen_ai.usage.*` attributes, adds its own `mlflow.chat.tokenUsage` on the chat span, and sums usage for the trace in its metadata, `mlflow.trace.tokenUsage`. The code reads the trace's total from that metadata: 331 [input tokens](#three-token-counts), 38 [output tokens](#three-token-counts) and 192 cache-read tokens. The total is checked to be the input plus the output, so the cache reads are not added twice.

MLflow priced nothing. At 3.18.0 it prices a span into `mlflow.llm.cost` and the trace into `mlflow.trace.cost` when its price lookup knows the model. It has no price for qwen3-4b-instruct-2507, the model the chat span names, so it stored no cost on either. Chapter 6 prices tokens with the book's own table, because the model is self-hosted and a price has a date.

Example `same-spans-two-receivers` (Python 3.13.16 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Send one message's spans, from one provider, to two receivers: the book's receiver and MLflow. Both hold the same span
IDs and the same attributes, and MLflow adds its own attributes under mlflow.*; the book's receiver adds none."""
import tempfile

from lib.assistant import AGENT, RELEASES
from lib.clock import VirtualClock
from lib.genai import SCHEMA_URL
from lib.ids import SequentialIds
from lib.mlflow_server import otlp_exporter, running, stored_spans
from lib.otlp import message_spans, start
from lib.tracing import make_provider

import mlflow
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

DAY, RELEASE = "2026-12-07", RELEASES["r0"]
receiver = start()                   # the book's receiver on loopback
clock = VirtualClock(DAY)
with tempfile.TemporaryDirectory() as folder, running(folder, "ambrewick-two-backends") as (uri, experiment):
    provider = make_provider(AGENT, RELEASE.service_version, "same-spans-two-receivers", clock, SequentialIds(),
                             InMemorySpanExporter(), SCHEMA_URL)
    provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint=receiver.endpoint)))
    provider.add_span_processor(SimpleSpanProcessor(otlp_exporter(uri, experiment)))
    message_spans(provider.get_tracer("ambrewick.assistant"), clock)
    found = mlflow.search_traces(locations=[experiment])

book = {row["span_id"]: row for row in receiver.rows()}
other = {span["span"]: span for span in stored_spans(found)}
receiver.stop()
assert len(book) == len(other) == 3 and set(book) == set(other)  # the same spans in both
added = set()
for span_id, row in book.items():
    kept = {key: value for key, value in other[span_id]["attributes"].items() if not key.startswith("mlflow.")}
    assert kept == row["attributes"]  # every attribute the book stored is still there, unchanged
    assert not any(key.startswith("mlflow.") for key in row["attributes"])  # the book's rows hold no mlflow.* keys
    added |= set(other[span_id]["attributes"]) - set(row["attributes"])

print("spans received by the book's receiver:", len(book))
print("spans received by MLflow:", len(other))
print("the same span IDs in both: yes (asserted)")
print("the book's attributes equal in both, on every span: yes (asserted)")
print("attributes MLflow adds, by name:", ", ".join(sorted(added)))
print("mlflow.* attributes in the book's rows: none (asserted)")
```

Output:

```text
spans received by the book's receiver: 3
spans received by MLflow: 3
the same span IDs in both: yes (asserted)
the book's attributes equal in both, on every span: yes (asserted)
attributes MLflow adds, by name: mlflow.chat.tokenUsage, mlflow.llm.model, mlflow.llm.provider, mlflow.spanType, mlflow.traceRequestId
mlflow.* attributes in the book's rows: none (asserted)
```

One provider can carry two processors, so the same spans can reach the receiver and MLflow in one run. The receiver and MLflow hold the same span IDs, and every attribute the receiver stored is in MLflow's copy unchanged, once MLflow's JSON-text values are decoded. MLflow adds mlflow.chat.tokenUsage, mlflow.llm.model, mlflow.llm.provider, mlflow.spanType, mlflow.traceRequestId, all under `mlflow.`, and the receiver's rows hold none of them.

MLflow's docs at this version name no flag for its GenAI conventions, but the code has `MLFLOW_ENABLE_OTEL_GENAI_SEMCONV`. At 3.18.0 the flag is read only by MLflow's own client-side span processor (`mlflow/tracing/processor/otel.py`), before MLflow's SDK exports the spans it made itself. The server's ingest route never reads it. So the flag governs how MLflow's SDK exports its own spans, not what the server stores from the book's exporter, and the book's path never reaches it.

**Working rule:** Give each backend its own exporter, and check its stored span IDs and attributes against the exporter's before you trust its queries. Set the experiment header on the OTLP exporter, search with `locations`, decode the span IDs, and read the trace's total from its metadata. In production we recommend a backend that keeps its rows on disk and is checked against the exporter, because a query is only as good as the rows it reads. The cost is one more service to run and keep.

## What the other backends say {#what-others-do}

MLflow is one backend these spans reach unchanged. Four others are named here as places the same names might go: Langfuse, Arize Phoenix, Jaeger and Datadog. We ran none of them. Each paragraph gives the date or version of the page we read and what that page says. A page's claim is the vendor's, and this book does not rank the four.

Langfuse's [OpenTelemetry integration page](https://langfuse.com/integrations/native/opentelemetry), which is undated, says that it accepts OTLP at a `/api/public/otel` path, over HTTP with JSON or with protobuf, and that it does not support gRPC. It uses Basic authentication with a key pair. It maps some `gen_ai.*` attributes to its own fields, and it says its own `langfuse.*` attributes take precedence. The mapping names `gen_ai.prompt` and `gen_ai.completion`, which are older names than the `gen_ai.input.messages` that chapter 3's [capture switch](#the-capture-switch) writes. The page says Langfuse aims to be compliant with the GenAI conventions, and gives no version for them.

Arize Phoenix's release note of 2026-05-15 says that Phoenix converts incoming `gen_ai.*` attributes to OpenInference attributes when spans arrive. The statements in this paragraph are from arize-phoenix 15.10.0, per that release note. Conversion fills in only what is missing, so an attribute that is already OpenInference wins, and the note names no flag to turn it off or on. Phoenix's own Python setup sends spans with [OpenInference](#two-other-naming-schemes) conventions. Phoenix takes spans at `POST /v1/traces`, in protobuf only, sent as `application/x-protobuf` with gzip or deflate, so unlike Langfuse it takes no JSON. The route is in [`traces.py`](https://raw.githubusercontent.com/Arize-ai/phoenix/arize-phoenix-v22.0.1/src/phoenix/server/api/routers/v1/traces.py) at tag `arize-phoenix-v22.0.1`. Phoenix's [licence](https://raw.githubusercontent.com/Arize-ai/phoenix/arize-phoenix-v22.0.1/LICENSE) begins "Elastic License 2.0 (ELv2)", and that is one reason the book does not depend on it.

Jaeger's documentation at version 2.23 describes Jaeger as a distribution of the OpenTelemetry Collector framework, on its [architecture page](https://www.jaegertracing.io/docs/2.23/architecture/). Its OTLP receiver, in the same documentation, accepts spans sent over OTLP. The storage options on its pages are Badger, Cassandra, ClickHouse, Elasticsearch, Memory and OpenSearch, and Kafka, which sits in front of storage as a persistent queue rather than as a store. The pages we read say nothing about GenAI spans, so this chapter makes no claim about Jaeger and GenAI.

Datadog's [OpenTelemetry ingestion page](https://docs.datadoghq.com/llm_observability/instrumentation/otel_instrumentation/), which is undated, says that it accepts OTLP traces directly, without a Datadog Agent or its Agent Observability SDK, provided conversion is enabled. Conversion is enabled by the resource attribute `dd_llmobs_enabled=true` or by the export header `DD-LLMObs-Enabled: true`. A trace is eligible only when its spans follow the OpenTelemetry GenAI conventions from version 1.37 onward, or OpenInference, and carry one of a short list of attributes. The page does not say whether the GenAI conventions at v0.1.0, which the book writes, count as 1.37 onward. The page says spans can take three to five minutes to appear.

**Working rule:** When a backend says it reads the OpenTelemetry names, find out which names it maps, at what version, and on what date, before a team relies on the claim. When the page gives no version or date, say so beside the claim.

## Changing the backend {#changing-backends}

Neither the receiver nor MLflow needed anything between the exporter and the store, and the OpenTelemetry Collector is what usually sits there. Its [overview](https://opentelemetry.io/docs/collector/) calls it a "vendor-agnostic way to receive, process and export telemetry data", and its [components page](https://opentelemetry.io/docs/collector/components/) lists five kinds of component: receivers, processors, exporters, connectors and extensions. Both pages were opened 2026-11-23 and are unversioned. The Collector's receivers are one of those five kinds of component. They are not the book's receiver, which is a server of the book's own.

The overview also allows a small setup to go without a Collector, and this book follows that. Here spans go straight to the book's receiver or to MLflow, both of which take OTLP directly, and this chapter does not run a Collector.

Changing a backend is therefore a change to the exporter. The two-receiver run in [MLflow on SQLite](#mlflow-on-sqlite) already sent one provider's spans to two receivers, by adding a second processor and leaving the span code as it was. The attributes in both places match. That is the whole move: the instrumentation and the spans stay the same, and the endpoint and header on the exporter say where they go.

The Collector has two jobs in the rest of the book, and the book names each where it arrives. Chapter 11 decides which whole traces to keep, which needs every span of a trace in one place. The tail-sampling processor's README at contrib `v0.140.0` gives the reason: "All spans for a given trace MUST be received by the same collector instance for effective sampling decisions." This book's receiver is where chapter 11 runs that decision in the examples, and a production Collector is what runs it. Chapter 12 removes personal data from spans before they leave the process. The Collector's overview lists [sensitive data filtering](https://opentelemetry.io/docs/collector/) among what a Collector does, so it is a place the same step can run. Chapter 12 places [redaction](#redaction-as-defence-in-depth) in the process first, so the Collector is a second defence, not a replacement.

**Working rule:** Set the endpoint and headers on the exporter, and leave the span code alone, so that changing a backend is a settings change. Add a Collector when a rule has to see whole traces or change data before it leaves, and not before. A small setup can do without one. We add no Collector until a rule needs whole traces, because a Collector is one more hop to run and keep working, and the book pays that cost only when a rule needs it.

## What goes wrong in production {#send-to-a-backend-in-production}

Chapter 1 named the batch processor as the production choice, and this chapter's exporter shows why. With the simple processor, a slow or closed endpoint holds the request that ends a span, for about 7 seconds at the default timeout, in the probe that [The exporter sends each span over OTLP](#otlp-over-http) describes. With the batch processor, the export runs on the processor's own schedule, so the request does not wait. The batch processor's cost is the one chapter 1 named: spans still in its queue are lost if the process dies. A server that writes its spans through a batch must flush them before it exits, as [The contacts server is another process](#the-contacts-server) explains for the contacts server.

The other failure is quieter, and the application never sees it: the exporter logs a lost batch and moves on. A batch larger than the exporter's default request limit of 64 MiB is also dropped whole and not split, according to the package's source. In production, the exporter's log is therefore where a lost batch shows up, and a team that wants to know about losses has to read it or alert on it.

**Working rule:** In production, keep the batch processor, make sure each server flushes before it exits, and read the exporter's log for dropped batches. Do not rely on the application to report a loss, because the exporter does not raise one to it.

## What this chapter decided {#send-to-a-backend-decisions}

- We send each process's spans to a receiver over OTLP/HTTP, and we run no Collector in the book's path. A Collector is not required at this scale, and chapters 11 and 12 can say where one would sit without running one.
- The book's receiver keeps rows in memory for a run, and MLflow keeps them on disk in SQLite. Both hold the exporter's spans, with the same IDs and attributes, and every later query reads the receiver's rows.
- The printed checks run on the simple processor, which hands every span to the exporter as it ends. Production uses the batch processor.
- The join and the orphan count are printed as numbers, not left to a reader's eye, so a change that breaks the join shows up as a count that moves.
- Each backend has its own exporter, and the rows it stores are checked against the exporter's, as the last bullet says.
- The named backends are described from the pages we read, with their dates or versions, and none is run or ranked.
- The MLflow GenAI flag stays off, because it does not apply to the book's path.
- A backend's claim to read the OpenTelemetry names is checked by comparing its stored rows with the exporter's, not read off its page.

# Attribute tokens and cost to each step

By the end of this chapter you can split a day's model calls into input tokens, cached input tokens and output tokens, total them without counting any token twice, and say which step, route and user the money went to. You can also say which of those numbers depends on a price table and which does not.

Ambrewick's finance team asks two questions of the assistant's traces. The first is what one message costs, by route and by user. It sounds like a sum over the spans, and it is the question that goes wrong first: usage sits on more than one kind of span, so a sum over all of them is too high. The second is what the same messages would cost in other languages. This book's assistant serves English only, but the dataset's other locales hold the same utterances, and the same utterance takes a different number of tokens in each language. The chapter measures both on one day, baseline day 1, 2026-12-08, which holds 200 messages. Each message ran through the assistant on the baseline release, with Qwen3-4B-Instruct-2507 as the model, and each model call was recorded once and replayed on the virtual clock, as [chapter 1](#replay-and-the-virtual-clock) describes.

Tokens come first, because they are what the model did. Money comes second, because it needs a price, and the price is a choice the book makes and dates.

## Three counts for each call {#three-token-counts}

A token count is the number of tokens a model reads or writes for one call, in that model's own vocabulary. The book keeps three counts for each call. Input tokens are the whole prompt the model read, cached part included; cached input tokens are the part its cache held; output tokens are what it wrote. The GenAI conventions, at version 0.1.0, define the input total the same way: `gen_ai.usage.input_tokens` includes the cached tokens. So the cached count sits inside the input count, and adding the two together counts the cached part twice.

The [prompt count and completion count](https://rollingedition.com/agent-harnesses/s/token-counts) in Agent Harnesses are close to these two, and they have no cached part. This book adds one, and it adds a price to the counts later in the chapter.

Each message makes one route call, and a message on any route but `fallback` makes one or more answer calls. The most calls one message made on this day is 3: a route call and two answer calls, when a tool's request comes before the reply. The script below sorts every call of the day by its three counts and its step.

Example `token-counts-per-step` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Tokens per model call (a request), per message, per resolved message and per route, over baseline day 1's 200
messages. Each rate names its denominator (PL-11): a resolved message is one the model answered, not the fallback reply.
The input count includes the cached part, so the cached share is printed beside it."""
from lib.dayrun import run_day
from lib.report import fmt_int, fmt_share

runs = run_day("2026-12-08")
model_steps = {run.message.message_id: [s for s in run.outcome.steps if s.name == "chat"] for run in runs}


def totals(steps):
    """Input (cached part included), cached input (derived) and output tokens, summed over some model steps."""
    return (sum(s.prompt_tokens for s in steps), sum(s.cached_tokens for s in steps),
            sum(s.completion_tokens for s in steps))


requests = [s for steps in model_steps.values() for s in steps]
inp, cached, out = totals(requests)
print("messages:", fmt_int(len(runs)))
print("requests (model calls):", fmt_int(len(requests)))
print("input tokens, total:", fmt_int(inp))
print("cached input tokens, derived, total:", fmt_int(cached))
print("output tokens, total:", fmt_int(out))
print("cached share of input tokens:", fmt_share(cached, inp))
print("input tokens per request:", f"{inp / len(requests):.1f}")
print("output tokens per request:", f"{out / len(requests):.1f}")
print("input tokens per message:", f"{inp / len(runs):.1f}")
# Every message makes a route call first; a fallback message stops there, so it has no answer call.
for step in ("route", "answer"):
    steps = [s for s in requests if s.step == step]
    print(f"{step} requests:", fmt_int(len(steps)))
    print(f"{step} requests, input tokens per request:", f"{totals(steps)[0] / len(steps):.1f}")
model_calls = {run.message.message_id: len(model_steps[run.message.message_id]) for run in runs}
assert all(sum(s.step == "route" for s in model_steps[m]) == 1 for m in model_calls)   # one route call per message
print("most model calls in one message:", max(model_calls.values()))   # the route call and up to two answer calls
resolved = [run for run in runs if run.outcome.source == "model"]
r_inp, _, r_out = totals([s for run in resolved for s in model_steps[run.message.message_id]])
print("resolved messages:", fmt_int(len(resolved)))
print("input tokens per resolved message:", f"{r_inp / len(resolved):.1f}")
print("output tokens per resolved message:", f"{r_out / len(resolved):.1f}")
for route in sorted({run.outcome.route for run in runs}):
    mine = [run for run in runs if run.outcome.route == route]
    route_inp, _, route_out = totals([s for run in mine for s in model_steps[run.message.message_id]])
    print(f"route {route}, messages:", fmt_int(len(mine)))
    print(f"route {route}, input tokens per message:", f"{route_inp / len(mine):.1f}")
    print(f"route {route}, output tokens per message:", f"{route_out / len(mine):.1f}")
assert sum(totals(steps)[0] for steps in model_steps.values()) == inp   # every request belongs to exactly one message
```

Output:

```text
messages: 200
requests (model calls): 321
input tokens, total: 104,811
cached input tokens, derived, total: 61,460
output tokens, total: 4,996
cached share of input tokens: 58.6%
input tokens per request: 326.5
output tokens per request: 15.6
input tokens per message: 524.1
route requests: 200
route requests, input tokens per request: 145.5
answer requests: 121
answer requests, input tokens per request: 625.6
most model calls in one message: 3
resolved messages: 111
input tokens per resolved message: 827.7
output tokens per resolved message: 40.2
route alarms, messages: 16
route alarms, input tokens per message: 883.6
route alarms, output tokens per message: 43.4
route calendar, messages: 27
route calendar, input tokens per message: 903.5
route calendar, output tokens per message: 38.8
route devices, messages: 17
route devices, input tokens per message: 627.9
route devices, output tokens per message: 44.5
route fallback, messages: 89
route fallback, input tokens per message: 145.4
route fallback, output tokens per message: 6.0
route lists, messages: 13
route lists, input tokens per message: 936.5
route lists, output tokens per message: 29.0
route media, messages: 31
route media, input tokens per message: 663.9
route media, output tokens per message: 41.6
route messages, messages: 7
route messages, input tokens per message: 1415.4
route messages, output tokens per message: 42.1
```

Most of the day's input is cached. Of 104,811 input tokens across the day's model calls, 61,460 were cached, which is 58.6% of the input. The output is small by comparison, 4,996 tokens in all.

The two steps differ in size. A route request reads 145.5 input tokens on average, and an answer request reads 625.6, because the answer call carries more of the prompt, such as the retrieved articles and a tool's result.

Input tokens are the call's messages rendered through the chat template in the model's GGUF file and re-tokenized with the model's own tokenizer. Output tokens are the reply re-tokenized with the model's own tokenizer. Cached input is derived rather than reported, as [chapter 1](#replay-and-the-virtual-clock) says, and the cached-input section below shows the subtraction.

Divided by the messages, the day's input is 524.1 tokens per message. Per resolved message it is 827.7 input and 40.2 output tokens. A resolved message is one the assistant answered with a model reply, not a fallback reply. Each rate here names its denominator, because a count per request and a count per message answer different questions.

**Working rule:** Report a call's input as the whole prompt, cached part included, and report cached input beside it, never added to it. Give output on its own. Name the count's source beside any token total, because the same text takes a different number of tokens in a different vocabulary.

## Summing spans double counts {#totals-from-metrics-not-spans}

The obvious way to total a day's tokens is to add the usage on every span. That is the sum a backend's query would run first, and here it is wrong. The [conventions' note on aggregating token usage](https://raw.githubusercontent.com/open-telemetry/semantic-conventions-genai/v0.1.0/docs/gen-ai/gen-ai-token-metrics.md) says not to sum `gen_ai.usage.*` over all spans without filtering by operation name, because the same tokens can be reported on more than one type of span, such as an agent span and an inference span. Usage sits on each model call's inference span, and the assistant also sets the message's total on its agent span, as the conventions allow. [Chapter 2](#span-types-for-each-step) names both span types.

Adding the usage up three ways over the same day shows where the extra comes from.

Example `totals-metric-against-spans` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Summing usage over every span counts each input token twice, because the agent span carries its message's usage as well as
its model calls do (the registry's aggregation note). The assistant's live meter counts each call once, as the call ends,
and matches the inference spans. The two asserts are the facts the prose relies on."""
from lib.dayrun import RELEASE, run_day_traced
from lib.metrics import PER_OPERATION, USAGE, make_meter_provider, totals
from lib.names_map import NAMES, REGISTRY_VERSION
from lib.report import fmt_int
from opentelemetry.sdk.metrics.export import InMemoryMetricReader

DAY = "2026-12-08"
INPUT = "gen_ai.usage.input_tokens"
reader = InMemoryMetricReader()
provider = make_meter_provider(reader, service_instance_id=f"{DAY}-metrics", service_version=RELEASE.service_version)
traced = run_day_traced(DAY, live=False, meter_provider=provider)   # the assistant records each call's tokens as it ends
attributes = [s["attributes"] for s in traced.spans]
inference = [a for a in attributes if a.get("gen_ai.operation.name") == "chat"]
agents = [a for a in attributes if a.get("gen_ai.operation.name") == "invoke_agent"]   # one per message


def summed(rows, key):
    """The sum of one usage attribute over span attributes; a span without it adds zero."""
    return sum(row.get(key, 0) for row in rows)


got = totals(reader)
spans_input = summed(inference, INPUT)
every_span_input = summed(attributes, INPUT)
counter_input = int(got[USAGE["input"]]["sum"])
print("messages:", fmt_int(len(traced.runs)))
print("inference spans, one per model call:", fmt_int(len(inference)))
print("agent spans, invoke_agent, one per message:", fmt_int(len(agents)))
print("input tokens, summed over the inference spans:", fmt_int(spans_input))
print("input tokens, summed over every span:", fmt_int(every_span_input))
print("input tokens, token counter total:", fmt_int(counter_input))
print("input tokens, per-operation histogram sum:", fmt_int(int(got[PER_OPERATION["input"]]["sum"])))
print("per-operation histogram, count of operations:", fmt_int(got[PER_OPERATION["input"]]["count"]))
print("output tokens, token counter total:", fmt_int(int(got[USAGE["output"]]["sum"])))
print("GenAI conventions version:", REGISTRY_VERSION)
print("package token histogram, gen_ai.client.token.usage, v0.1.0 names:", ", ".join(NAMES["gen_ai.client.token.usage"]))
assert every_span_input == 2 * spans_input      # the agent spans repeat every inference token once more
assert counter_input == spans_input             # the counter reads each call's usage once, as the call ends
```

Output:

```text
messages: 200
inference spans, one per model call: 321
agent spans, invoke_agent, one per message: 200
input tokens, summed over the inference spans: 104,811
input tokens, summed over every span: 209,622
input tokens, token counter total: 104,811
input tokens, per-operation histogram sum: 104,811
per-operation histogram, count of operations: 321
output tokens, token counter total: 4,996
GenAI conventions version: 0.1.0
package token histogram, gen_ai.client.token.usage, v0.1.0 names: gen_ai.client.inference.operation.input_tokens, gen_ai.client.inference.operation.output_tokens
```

The assistant records each model call's tokens on its meter as the call ends, and the book reads two instruments from that meter. A metric is a measurement the SDK aggregates over many operations and exports without each one's detail; a counter only adds, and a histogram counts values into buckets with their sum and count. The input-token counter, `gen_ai.client.inference.usage.input_tokens`, gives one total for the day. The per-operation histogram records one value for each model call, its input tokens, and keeps their sum and their count.

Summed over the inference spans, the input is 104,811 tokens. Summed over every span, it is 209,622. The second figure is the first with the agent spans' copy added, so it is too high by exactly that copy. The token counter, which the assistant adds to on each model call, gives 104,811, the same total as the inference spans. The point to keep is that the counter and the inference spans agree, and the sum over every span does not.

The per-operation histogram's sum is 104,811 over 321 operations, the model calls, which matches the counter. The output counter gives 4,996 output tokens.

The package this book uses writes an older token metric: one histogram, `gen_ai.client.token.usage`, that splits by `gen_ai.token.type`. [Chapter 3](#what-the-package-emits) shows its names beside the registry's, and in v0.1.0 that histogram's names are gen_ai.client.inference.operation.input_tokens, gen_ai.client.inference.operation.output_tokens. The counters split by `gen_ai.token.modality` instead, and for each operation the modality counts add up to the total. The conventions' note says that the token counters are not affected by trace sampling, so a total read from them survives a sampler that drops spans, and a total read from spans does not. A counter filled at each call counts every call whatever a sampler keeps; a total rebuilt from sampled spans falls with the sample, and must be scaled up, with an [error](#how-a-span-records-failure), as [chapter 11](#estimating-totals-from-a-sample) shows.

**Working rule:** Take a day's token total from the counters, or sum usage over inference spans only, filtered by operation name. Usage on an agent span is that agent's total over its calls, so never add it to the calls' usage. In production we read totals from the counters, because a sampler cannot thin them.

## Cached input, derived from the counters {#cached-prompt-tokens}

The runtime does not report the reused count, so the book derives it: cached input is the prompt tokens minus the tokens the runtime evaluated. Reuse happens in two places. The runtime keeps the evaluated prefix of the last prompt, and a call whose prompt starts with the same tokens evaluates only the new suffix; the baseline also turns on a RAM cache, `PromptCache(LlamaRAMCache)` with `cache_prompt: true`, which restores the saved state of an earlier prompt with the longest shared prefix once the context's own prefix has been overwritten. The assistant's system prompt and its tool list sit at the front of every prompt, so most calls reuse them.

The pinned llama-cpp-python 0.3.37 has no cached-token field in its Python API or in the performance counters it ships. The recorder takes `n_p_eval`, the prompt tokens evaluated, as a difference between calls, because the counters accumulate. The counter `n_reused` sits in the same structure, but it counts graph reuse, not tokens, so this book does not read it as the cached count. We judge that a derived count of reused prefix tokens belongs in `gen_ai.usage.cache_read.input_tokens` and the cache-read counter, and we record a zero when nothing is reused. The registry defines that attribute as tokens served from a provider-managed cache, as the provider reports them, so the count is the book's own judgement and not a provider's report.

The same 60 messages run twice here, a seeded sample of baseline day 1: once on the baseline release, `r0`, and once on the cache-off release, `r4`. Release `r4` differs from `r0` in two ways. Its RAM cache is off, and `llm.reset()` clears the runtime's state before each call, which is the way the book's recorder gives each call a fresh state. Setting the cache to none is not enough, because the next call still reuses the prefix of the last one, as the book's probe at the pinned version found.

Example `cached-tokens-from-replay` (Python 3.13.16 · bm25s 0.3.16 · huggingface-hub 2.4.0 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3), passing in Edition 2026.11.2:

```python
"""Cached input tokens for each model call, derived as prompt tokens minus the tokens llama.cpp evaluated (PL-21), on baseline
day 1 and on the same 60 messages with the prompt cache reset before each call (release r4). The reset leaves the input
tokens the model reads unchanged; what it removes is the cached part, so the same tokens are all evaluated again. Each call
is priced at its own start on the replay clock."""
from decimal import Decimal

from lib.case import load_messages
from lib.dayrun import run_day
from lib.prices import PriceTable
from lib.report import fmt_int, fmt_share, fmt_usd
from lib.tokens import derived_cached, recorded_calls

DAY, MODEL = "2026-12-08", "Qwen3-4B-Instruct-2507"
paired = {m.message_id for m in load_messages("2026-12-08-paired")}   # the 60 messages r1, r3 and r4 replay
day = recorded_calls("baseline-day-1")
day_input, _, day_cached = derived_cached(day)
print("baseline day 1, model calls:", fmt_int(len(day)))
print("baseline day 1, input tokens, total:", fmt_int(day_input))
print("baseline day 1, cached input tokens, derived, total:", fmt_int(day_cached))
print("baseline day 1, cached share of input:", fmt_share(day_cached, day_input))
# The recorder's own derived field is the same subtraction, call by call.
assert all(c["cached_tokens_derived"] == c["prompt_tokens"] - c["tokens_evaluated"] for c in day)

base = recorded_calls("baseline-day-1", paired)
cache_off = recorded_calls("release-cache-off", paired)
assert [(c["message_id"], c["step"]) for c in base] == [(c["message_id"], c["step"]) for c in cache_off]  # the same calls
b_input, b_evaluated, b_cached = derived_cached(base)
o_input, o_evaluated, o_cached = derived_cached(cache_off)
print("same 60 messages, model calls:", fmt_int(len(base)))
print("r0, input tokens:", fmt_int(b_input))
print("r0, tokens evaluated:", fmt_int(b_evaluated))
print("r0, cached input tokens, derived:", fmt_int(b_cached))
print("r4, input tokens:", fmt_int(o_input))
print("r4, tokens evaluated:", fmt_int(o_evaluated))
print("r4, cached input tokens, derived:", fmt_int(o_cached))
print("tokens evaluated, r4 minus r0:", fmt_int(o_evaluated - b_evaluated))
assert o_input == b_input and o_cached == 0          # same input tokens; the cache reset leaves no cached part
assert o_evaluated - b_evaluated == b_cached         # every cached token is evaluated again without the cache

# The same calls at the book's rates. A recorded call has no clock of its own, so each takes the start the baseline replay
# gave its message and step, and r4 makes the same calls, so its calls take the same starts.
starts = {(run.message.message_id, s.step): s.start_ns for run in run_day(DAY, paired)
          for s in run.outcome.steps if s.name == "chat"}
price = PriceTable()


def money(calls):
    """The money of recorded calls at the book's rates, each at its own start."""
    return sum((price.cost(MODEL, c["prompt_tokens"], c["cached_tokens_derived"], c["completion_tokens"],
                           starts[(c["message_id"], c["step"])]) for c in calls), Decimal(0))


print(f"cost difference, r4 minus r0, same 60 messages, {price.version}:", fmt_usd(money(cache_off) - money(base)))
```

Output:

```text
baseline day 1, model calls: 321
baseline day 1, input tokens, total: 104,811
baseline day 1, cached input tokens, derived, total: 61,460
baseline day 1, cached share of input: 58.6%
same 60 messages, model calls: 93
r0, input tokens: 29,107
r0, tokens evaluated: 11,682
r0, cached input tokens, derived: 17,425
r4, input tokens: 29,107
r4, tokens evaluated: 29,107
r4, cached input tokens, derived: 0
tokens evaluated, r4 minus r0: 17,425
cost difference, r4 minus r0, same 60 messages, book-2026-11-02: $0.001394
```

Under the baseline the 60 messages read 29,107 input tokens, and only 11,682 of them were evaluated; the rest were cached. Under the cache-off release they read the same 29,107 tokens, and all of them were evaluated. Resetting the state did not change what the model read; it changed how much of it the runtime had to evaluate, so 17,425 more tokens were evaluated.

That difference is the money. At the book's table the cache-off release [costs](#cost-per-route) $0.001394 more on those 60 messages, because cached tokens are billed at the cached rate and evaluated ones at the input rate. A release which changes the cache changes cost and leaves input tokens alone, so a comparison of input tokens would miss that change.

**Working rule:** Derive cached input at each call from the runtime's counters, never from a release's label. When a release changes the cache, we compare cost on the same messages, because the input count will not move.

## The same utterances in other languages {#the-same-requests-in-other-languages}

Tokens are counted per vocabulary, and the same text can take very different numbers of tokens in different languages. Petrov and colleagues measured the gap for several tokenizers, found differences of up to fifteen times in some language pairs, and found the gap persisted in tokenizers built for many languages, as [their NeurIPS 2023 paper](https://arxiv.org/abs/2305.15425) reports. This section measures the gap for the dataset's utterances.

Only the English messages ran through the assistant. The other five locales are the same 200 utterances in the dataset's other locale files, joined by id. No model read them and no assistant served them, so each cost is an input rate on that text. The six locales are English (en-US), German (de-DE), Japanese (ja-JP), Hindi (hi-IN), Arabic (ar-SA) and Chinese (zh-CN). The example counts all six with the tokenizer file of the model the book uses, and prices the counts at [the book's table](#the-price-table).

Each locale's count is the tokenizer file's count: the utterance's text alone, normalised to NFC and tokenized by `tokenizers` 0.23.3 with the 4B's `tokenizer.json`; no model read it, and it is not a whole prompt.

Example `count-locales-with-the-tokenizer` (Python 3.13.16 · huggingface-hub 2.4.0 · numpy 2.5.5 · tokenizers 0.23.3), passing in Edition 2026.11.2:

```python
"""Count the same 200 baseline utterances in six locales with the 4B's own tokenizer file, and price the counts at the book's
input rate. The printed hi-IN ratio is the point the prose rests on: the same request takes several times the English
tokens. Each count is the utterance's text alone, not a whole prompt."""
from decimal import Decimal

from lib.case import load_locale, load_messages
from lib.clock import VirtualClock
from lib.prices import PriceTable
from lib.report import fmt_int, fmt_usd
from lib.tokens import LocaleCounter, is_nfc

DAY = "2026-12-08"
MODEL = "Qwen3-4B-Instruct-2507"
LOCALES = ("en-US", "de-DE", "ja-JP", "hi-IN", "ar-SA", "zh-CN")
messages = load_messages(DAY)
ids = [m.message_id for m in messages]
texts = {m.message_id: m.text for m in messages}
by_id = sorted(messages, key=lambda m: int(m.message_id))   # the order load_locale returns each locale's utterances in
arrivals = [VirtualClock(DAY, start_ns=m.arrival_ns).now_ns for m in by_id]   # each message's own arrival, on the day's clock
counter, price = LocaleCounter(), PriceTable()

print("price table:", price.version)
print("utterances, the baseline day's messages joined by id:", fmt_int(len(ids)))
means = {}
for locale in LOCALES:
    utterances = load_locale(locale, ids)   # the same messages, in ascending ID order, so the locales line up
    counts = [counter.count(text) for text in utterances]
    total = sum(counts)
    means[locale] = total / len(counts)
    # The text is not cached, so every token bills at the input rate, each utterance at its message's arrival.
    per_thousand = sum((price.cost(MODEL, n, 0, 0, at) for n, at in zip(counts, arrivals)), Decimal(0)) * 1000 / len(counts)
    print(f"{locale}, tokens, total:", fmt_int(total))
    print(f"{locale}, tokens per utterance:", f"{means[locale]:.1f}")
    print(f"{locale}, input cost per 1,000 utterances, {price.version}:", fmt_usd(per_thousand))

print("hi-IN tokens per utterance, as a multiple of en-US:", f"{means['hi-IN'] / means['en-US']:.1f}")
hindi = load_locale("hi-IN", ids)
# NFC is applied by the tokenizer file, so only text that is not already NFC can count differently under another counter.
print(f"hi-IN utterances not in NFC, of {len(hindi)}:", sum(not is_nfc(text) for text in hindi))
assert [texts[i] for i in sorted(ids, key=int)] == load_locale("en-US", ids)  # the English texts are the traffic's own
assert all(is_nfc(t) for locale in LOCALES if locale != "hi-IN" for t in load_locale(locale, ids))
```

Output:

```text
price table: book-2026-11-02
utterances, the baseline day's messages joined by id: 200
en-US, tokens, total: 1,508
en-US, tokens per utterance: 7.5
en-US, input cost per 1,000 utterances, book-2026-11-02: $0.000754
de-DE, tokens, total: 2,194
de-DE, tokens per utterance: 11.0
de-DE, input cost per 1,000 utterances, book-2026-11-02: $0.001097
ja-JP, tokens, total: 1,979
ja-JP, tokens per utterance: 9.9
ja-JP, input cost per 1,000 utterances, book-2026-11-02: $0.000990
hi-IN, tokens, total: 6,864
hi-IN, tokens per utterance: 34.3
hi-IN, input cost per 1,000 utterances, book-2026-11-02: $0.003432
ar-SA, tokens, total: 2,015
ar-SA, tokens per utterance: 10.1
ar-SA, input cost per 1,000 utterances, book-2026-11-02: $0.001008
zh-CN, tokens, total: 1,314
zh-CN, tokens per utterance: 6.6
zh-CN, input cost per 1,000 utterances, book-2026-11-02: $0.000657
hi-IN tokens per utterance, as a multiple of en-US: 4.6
hi-IN utterances not in NFC, of 200: 8
```

The same 200 utterances cost 4.6 times as many tokens in Hindi as in English. The table gives each locale's count per utterance, and the input cost of 1,000 utterances at the book's table.

| Locale | Tokens per utterance | Input cost per 1,000 utterances |
| --- | --- | --- |
| English, en-US | 7.5 | $0.000754 |
| German, de-DE | 11.0 | $0.001097 |
| Japanese, ja-JP | 9.9 | $0.000990 |
| Hindi, hi-IN | 34.3 | $0.003432 |
| Arabic, ar-SA | 10.1 | $0.001008 |
| Chinese, zh-CN | 6.6 | $0.000657 |

The English utterances take 7.5 tokens each, and the Hindi ones take 34.3. A budget for input tokens written in English tokens is therefore wrong for a Hindi user, and the same holds for the cost of a request. The counts are of the utterance alone, so they understate a whole prompt in every locale. What carries into a budget is the ratio between locales, and that ratio should be measured on the traffic that will run.

Some of the Hindi text is not in the normal form the tokenizer expects. 8 of the 200 Hindi utterances are not in Unicode normalisation form NFC, as the [Unicode report on normalisation](https://unicode.org/reports/tr15/) defines it. The tokenizer file normalises them before counting. The GGUF tokenizer that llama.cpp uses applies no normalisation, so its count can differ from this one on those utterances, and at most 8 of the 200 can differ; the GGUF count was not run. This chapter prints the file's count and no other, and it says which counter each number comes from. The chapter quotes no utterance text, because no example prints it.

**Working rule:** Count each locale with the tokenizer that serves it, after the same normalisation, and name the counter beside every figure. Budget input in the locale's own tokens, and measure the locale's ratio on your own traffic before you rely on a multiple.

## The price table {#the-price-table}

Every money figure in this chapter comes from one file, the book's price table, `examples/data/case/prices.toml`, at version `book-2026-11-02`. The price table is a dated, versioned file of rates per million tokens, read at each call's virtual timestamp. For each model it gives rates in US dollars for input, cached input and output, and a date from which each row applies. The rows were written for this book, not quoted from any provider; each row says what a hosted endpoint would charge at those rates. The ratios matter most: on the 4B row, output costs 4.0 times input, and cached input 0.2 of input.

Hosted providers do not all report input the same way. Anthropic's `input_tokens` excludes cached tokens, and the conventions' [Anthropic note](https://raw.githubusercontent.com/open-telemetry/semantic-conventions-genai/v0.1.0/docs/gen-ai/anthropic.md) asks instrumentation to add them in, so a reader pricing such a provider normalises its fields to the registry's input total before pricing. Cache writes are counted apart, in `gen_ai.usage.cache_write.input_tokens`. The book's runtime writes no cache, so its table has no cache-write rate.

A self-hosted model is billed by its machine, not by its tokens. The table therefore attaches a money figure to a token count so that the book can compare requests. It is not a bill for the local model, and [Small Open Models](https://rollingedition.com/small-open-models/s/count-the-bill-and-the-machine) works out a machine's bill against per-token prices.

The nearest real price is the genai-prices listing, and it differs from the book's rows in three ways: it names a provider, it has no cache price, and it carries no date. genai-prices 0.2.5 lists the repository `Qwen/Qwen3-4B-Instruct-2507` under the provider `huggingface_nscale`, with an input rate and an output rate. With no cache price, the listing bills cached input at the input rate. The rates are the snapshot the library bundles, and the library makes no network call unless its updater is started. A lookup needs both the full repository name and `provider_id="huggingface_nscale"`: without the provider it raises `LookupError`, and so does a provider it does not list, as the example asserts. The listing has no text-model row for `Qwen3-0.6B`, so the book's 0.6B row has no source. The library's 4B row has no start date, and the book's probe at the pinned version found that it prices the same request the same on 2026-11-01, 2026-11-02 and 2026-12-08. So the 2026-11-02 date in the book's table is the book's own, and the library does not supply it.

One answer request from the day, priced three ways, shows how the tables differ.

Example `price-one-request` (Python 3.13.16 · bm25s 0.3.16 · genai-prices 0.2.5 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Price one answer call twice: at the book's own rates, and at the genai-prices 0.2.5 listing for the 4B, which needs its
provider and a virtual timestamp (B-59). The two prices differ because the rates differ; the book's rates were written
for the book and the listing is the real one, so the prose names which is which. Money prints with its table's version."""
from decimal import Decimal

from lib.dayrun import run_day
from lib.prices import PriceTable, datetime_of
from lib.report import fmt_int, fmt_usd
from genai_prices import Usage, calc_price

MODEL, LISTED = "Qwen3-4B-Instruct-2507", "Qwen/Qwen3-4B-Instruct-2507"   # the book's name, and the listing's repo name
runs = run_day("2026-12-08")
call = next(s for run in runs for s in run.outcome.steps if s.step == "answer")   # the day's first answer call
print("request, input tokens, total:", fmt_int(call.prompt_tokens))
print("request, cached input tokens, derived:", fmt_int(call.cached_tokens))
print("request, output tokens:", fmt_int(call.completion_tokens))

book = PriceTable()
money = book.cost(MODEL, call.prompt_tokens, call.cached_tokens, call.completion_tokens, call.start_ns)
no_cache = book.cost(MODEL, call.prompt_tokens, 0, call.completion_tokens, call.start_ns)
print(f"book's table, cached input at its own rate, {book.version}:", fmt_usd(money))
print(f"book's table, the same request with no cached input, {book.version}:", fmt_usd(no_cache))
row = book.row(MODEL, call.start_ns)   # the row in force at the call's start
print("book's table, output rate to input rate:", f"{Decimal(row['output_per_mtok']) / Decimal(row['input_per_mtok']):.1f}")
print("book's table, cached input rate to input rate:",
      f"{Decimal(row['cache_read_per_mtok']) / Decimal(row['input_per_mtok']):.1f}")

usage = Usage(input_tokens=call.prompt_tokens, cache_read_tokens=call.cached_tokens, output_tokens=call.completion_tokens)
when = datetime_of(call.start_ns)   # the call's virtual time, never the machine's clock
listed = calc_price(usage, LISTED, provider_id="huggingface_nscale", genai_request_timestamp=when)
print("genai-prices listing, huggingface_nscale, the same request:", fmt_usd(listed.total_price))


def lookup_fails(*args, **kwargs) -> bool:
    """True when genai-prices cannot find a price for the call: a LookupError, not a price from another model."""
    try:
        calc_price(*args, **kwargs)
    except LookupError:
        return True
    return False


# The listing has no cache price, so cached input bills at the input rate: the total does not change with the cache.
assert calc_price(Usage(input_tokens=call.prompt_tokens, output_tokens=call.completion_tokens), LISTED,
                  provider_id="huggingface_nscale", genai_request_timestamp=when).total_price == listed.total_price
assert lookup_fails(usage, LISTED, genai_request_timestamp=when)          # no provider given: no price
assert lookup_fails(usage, LISTED, provider_id="openai", genai_request_timestamp=when)   # the span's provider: no price
assert lookup_fails(usage, "Qwen/Qwen3-0.6B", provider_id="huggingface_nscale", genai_request_timestamp=when)
```

Output:

```text
request, input tokens, total: 212
request, cached input tokens, derived: 201
request, output tokens: 27
book's table, cached input at its own rate, book-2026-11-02: $0.000016
book's table, the same request with no cached input, book-2026-11-02: $0.000032
book's table, output rate to input rate: 4.0
book's table, cached input rate to input rate: 0.2
genai-prices listing, huggingface_nscale, the same request: $0.000003
```

The request reads 212 input tokens, most of them cached, and writes 27 output tokens. At the book's table it costs $0.000016. With the cache removed from the same request it would cost $0.000032, so the cache is what brings the bill down for this call.

The listing prices the same request at $0.000003. The gap between the two is the gap between the rate rows, since the tokens are the same in both.

A cost tool needs one more guard. The book's spans record `gen_ai.provider.name` as `openai`, because the assistant's client speaks OpenAI's API to a local server, as [chapter 2](#span-types-for-each-step) explains. A cost tool that reads that value could look up OpenAI's rates for a model OpenAI does not serve, and price the local model at OpenAI's rates. The listing fails loudly on that lookup, since it raises `LookupError` for the 4B under `openai`, so the risk is a tool that falls back to a default model or a fuzzy match. The book's table is keyed by model and does not read the provider value, and the listing is queried with its provider named by hand. A query that prices spans should do the same, and should never take the provider from the span. MLflow is one such tool: it prices a span only when its catalog knows the span's model, which is why it stored no cost for the 4B in [chapter 5](#mlflow-on-sqlite), and a self-hosted model reported under a hosted model's name could be priced at that model's rates.

The table's version and dates matter once a price changes. The release comparison in [chapter 10](#paired-comparison-on-messages) reads its money from this same table version, so one version holds every money figure that is compared.

**Working rule:** Attach a price table's version and its date to every money figure. Price each call at its own timestamp, and name the provider when you use a listing. Never take a provider from a span to choose the price. We key the book's table by model, and never by the span's provider.

## Cost by route and step {#cost-per-route}

A call's cost is its tokens priced by a named, dated price table, and cost attribution assigns each call's cost to the step, route and user that caused it. [Agent Harnesses](https://rollingedition.com/agent-harnesses/s/cost-not-money) stops its cost at counts on purpose; this book adds money, tokens first. The book computes cost at query time, from each call's tokens and the table, and does not store cost on the spans. A price change then reprices the query and leaves the stored spans as they were. [Chapter 1](#where-the-time-went-in-twenty-messages) asked which step costs the most money, and this section answers it.

Example `cost-by-route-and-user` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Cost by step, by route, per resolved message and per user on baseline day 1, at the book's rates. Each call is priced at
its own start, and the price row in force at that time is the one used (PL-20). Every rate names its denominator (PL-11):
messages sent to the route, messages the model resolved, or users. The fallback route makes a route call and no answer call."""
from collections import Counter
from decimal import Decimal

from lib.dayrun import run_day
from lib.prices import PriceTable
from lib.report import fmt_int, fmt_share, fmt_usd

MODEL = "Qwen3-4B-Instruct-2507"
runs = run_day("2026-12-08")
price = PriceTable()
cost, by_step = Counter(), Counter()   # Decimal money per message ID, and per step name
for run in runs:
    for step in (s for s in run.outcome.steps if s.name == "chat"):
        money = price.cost(MODEL, step.prompt_tokens, step.cached_tokens, step.completion_tokens, step.start_ns)
        cost[run.message.message_id] += money
        by_step[step.step] += money
total = sum(cost.values(), Decimal(0))
print("messages:", fmt_int(len(runs)))
print(f"cost, all messages, {price.version}:", fmt_usd(total))
for step in ("route", "answer"):
    print(f"{step} requests, cost, {price.version}:", fmt_usd(by_step[step]))
    print(f"{step} requests, share of cost:", fmt_share(by_step[step], total))
assert sum(by_step.values(), Decimal(0)) == total   # the two steps make up the whole cost

for route in sorted({run.outcome.route for run in runs}):
    mine = [run for run in runs if run.outcome.route == route]
    route_cost = sum((cost[run.message.message_id] for run in mine), Decimal(0))
    print(f"route {route}, messages:", fmt_int(len(mine)))
    print(f"route {route}, cost per 1,000 messages, {price.version}:", fmt_usd(route_cost * 1000 / len(mine)))

resolved = [run for run in runs if run.outcome.source == "model"]
resolved_total = sum((cost[run.message.message_id] for run in resolved), Decimal(0))
print("resolved messages:", fmt_int(len(resolved)))
print(f"cost of a resolved message, its own calls, {price.version}:", fmt_usd(resolved_total / len(resolved)))
by_user = Counter()                          # Decimal money per user ID
for run in runs:
    by_user[run.message.user_id] += cost[run.message.message_id]
assert sum(by_user.values(), Decimal(0)) == total   # the users make up the whole cost
costliest = max(sorted(by_user), key=by_user.get)   # ties go to the lower ID, so the choice is stable
print("users with a message:", fmt_int(len(by_user)))
print(f"cost per user, mean over users with a message, {price.version}:", fmt_usd(total / len(by_user)))
print("costliest user, messages:", fmt_int(sum(run.message.user_id == costliest for run in runs)))
print("costliest user, share of cost:", fmt_share(by_user[costliest], total))
```

Output:

```text
messages: 200
cost, all messages, book-2026-11-02: $0.007563
route requests, cost, book-2026-11-02: $0.001379
route requests, share of cost: 18.2%
answer requests, cost, book-2026-11-02: $0.006184
answer requests, share of cost: 81.8%
route alarms, messages: 16
route alarms, cost per 1,000 messages, book-2026-11-02: $0.063688
route calendar, messages: 27
route calendar, cost per 1,000 messages, book-2026-11-02: $0.057486
route devices, messages: 17
route devices, cost per 1,000 messages, book-2026-11-02: $0.056201
route fallback, messages: 89
route fallback, cost per 1,000 messages, book-2026-11-02: $0.006630
route lists, messages: 13
route lists, cost per 1,000 messages, book-2026-11-02: $0.074429
route media, messages: 31
route media, cost per 1,000 messages, book-2026-11-02: $0.057041
route messages, messages: 7
route messages, cost per 1,000 messages, book-2026-11-02: $0.101463
resolved messages: 111
cost of a resolved message, its own calls, book-2026-11-02: $0.000063
users with a message: 121
cost per user, mean over users with a message, book-2026-11-02: $0.000063
costliest user, messages: 3
costliest user, share of cost: 3.0%
```

The answer step costs most. Over the day's 200 messages, the answer requests cost $0.006184, which is 81.8% of the day's cost. The route requests cost $0.001379, or 18.2%. The route call is smaller, but every message makes one, so it still holds nearly a fifth of the money.

The routes differ in what a message costs. The table gives each route's messages, its tokens per message from the same day, and its cost per 1,000 messages. The denominator is the messages on each route.

| Route | Messages | Input tokens per message | Output tokens per message | Cost per 1,000 messages |
| --- | --- | --- | --- | --- |
| `alarms` | 16 | 883.6 | 43.4 | $0.063688 |
| `calendar` | 27 | 903.5 | 38.8 | $0.057486 |
| `devices` | 17 | 627.9 | 44.5 | $0.056201 |
| `fallback` | 89 | 145.4 | 6.0 | $0.006630 |
| `lists` | 13 | 936.5 | 29.0 | $0.074429 |
| `media` | 31 | 663.9 | 41.6 | $0.057041 |
| `messages` | 7 | 1415.4 | 42.1 | $0.101463 |

The `messages` route costs the most per message. It rests on 7 messages, though, so read it as one day's sample and not as a settled rate. The `fallback` route costs the least. Its reply is the fixed one that [chapter 1](#where-the-time-went-in-twenty-messages) describes, and its span records that no model wrote it. The route makes its one route call and no answer call, so its row carries the route call alone.

Example `figure-route-token-mix` (Python 3.13.16 · bm25s 0.3.16 · matplotlib 3.11.2 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Draw the input, cached and output tokens per message on each route, over baseline day 1's 200 messages. The cached part is
drawn inside the input bar, hatched, so no reader adds it to input; output stands beside it. Every bar is printed by route
with its message count, since a tokens-per-message rate names its denominator (PL-11)."""
from lib.dayrun import run_day
from lib.figures import ACCENT, INK, MUTED, new_figure, save
from lib.report import fmt_int

runs = run_day("2026-12-08")
routes = sorted({run.outcome.route for run in runs})
per_message = {}                            # route: (input, cached, output) tokens per message, as floats
for route in routes:
    mine = [run for run in runs if run.outcome.route == route]
    steps = [s for run in mine for s in run.outcome.steps if s.name == "chat"]   # model calls only; no tool time here
    averages = tuple(sum(values) / len(mine) for values in (
        [s.prompt_tokens for s in steps], [s.cached_tokens for s in steps], [s.completion_tokens for s in steps]))
    per_message[route] = averages
    print(f"route {route}, messages:", fmt_int(len(mine)))
    print(f"route {route}, input tokens per message:", f"{averages[0]:.1f}")
    print(f"route {route}, cached input tokens per message:", f"{averages[1]:.1f}")
    print(f"route {route}, output tokens per message:", f"{averages[2]:.1f}")

fig, ax = new_figure(height=2.8)
positions, width = list(range(len(routes))), 0.36
left, right = [p - width / 2 for p in positions], [p + width / 2 for p in positions]
cached = [per_message[r][1] for r in routes]
uncached = [per_message[r][0] - per_message[r][1] for r in routes]   # input minus its cached part, stacked on top of it
ax.bar(left, cached, width=width, color=MUTED, hatch="///", edgecolor=INK, label="cached input, part of input")
ax.bar(left, uncached, bottom=cached, width=width, color=ACCENT, label="input not cached")
ax.bar(right, [per_message[r][2] for r in routes], width=width, color=INK, label="output tokens")
ax.set_xticks(positions, routes)
ax.set_ylabel("tokens per message")
ax.set_ylim(0, 1.35 * max(v[0] for v in per_message.values()))   # headroom above the tallest bar for the legend
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.16), ncol=3, frameon=False)   # below the plot, clear of the top tick
save(fig, "route-token-mix")
```

Output:

```text
route alarms, messages: 16
route alarms, input tokens per message: 883.6
route alarms, cached input tokens per message: 525.3
route alarms, output tokens per message: 43.4
route calendar, messages: 27
route calendar, input tokens per message: 903.5
route calendar, cached input tokens per message: 604.9
route calendar, output tokens per message: 38.8
route devices, messages: 17
route devices, input tokens per message: 627.9
route devices, cached input tokens per message: 305.1
route devices, output tokens per message: 44.5
route fallback, messages: 89
route fallback, input tokens per message: 145.4
route fallback, cached input tokens per message: 128.9
route fallback, output tokens per message: 6.0
route lists, messages: 13
route lists, input tokens per message: 936.5
route lists, cached input tokens per message: 385.3
route lists, output tokens per message: 29.0
route media, messages: 31
route media, input tokens per message: 663.9
route media, cached input tokens per message: 325.1
route media, output tokens per message: 41.6
route messages, messages: 7
route messages, input tokens per message: 1415.4
route messages, cached input tokens per message: 711.7
route messages, output tokens per message: 42.1
figure: figures/route-token-mix.svg
```

Figure 6.1 shows each route's input tokens per message, with the cached part inside the input bar, and its output tokens beside it. A route can be cheap in output and still expensive in prompt.

*Figure 6.1. Input, cached input and output tokens per message, by route. The fallback route's bars are its route call alone.*

![Each route's input tokens per message, with the cached part hatched inside the input bar, and its output tokens beside it. The messages route's input is the tallest bar, and every route's output is short.](https://rollingedition.ai/books/observability-for-llm-applications/2026.11.2/figures/route-token-mix.svg)

Figure 6.1 shows that the lists route writes the least output of any route but the fallback route, 29.0 tokens per message, and still reads 936.5 input tokens per message. The messages route reads 1415.4 input tokens per message, of which 711.7 are cached. Every route reads far more than it writes.

Two per-unit figures close the section, each with its denominator. A [resolved message](#three-token-counts) costs $0.000063 in its own calls, over the 111 messages the model answered. Per user, the day costs $0.000063 on average, over the 121 users who sent a message that day.

The costliest of those users sent 3 messages and holds 3.0% of the day's cost.

**Working rule:** Attribute each call's cost to its step, route and user from each call's recorded counts, print each share beside its total, and name the denominator of every per-unit rate. Read a route's rate with its message count beside it, because a route with a handful of messages can move a lot from one day to the next. For the finance question we report each route's rate, not one mean over the day, because the money differs by route.

## The expensive tail {#the-expensive-tail}

An average hides the few messages that cost much more than the rest. The check is to rank the messages by cost and ask what share of the day's money the top 1% holds. With 200 messages, the top 1% is two messages.

Example `expensive-tail-share` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""The most expensive 1% of baseline day 1's messages, and their share of the day's cost at the book's rates. The count is
exact over the day's 200 messages, with no interval: an interval for another day is chapter 7's. The count is the
nearest-rank count for 1% of n (PL-5), and equal costs are ordered by message ID so the choice is stable."""
import math
from decimal import Decimal
from fractions import Fraction

from lib.dayrun import run_day
from lib.prices import PriceTable
from lib.report import fmt_int, fmt_share, fmt_usd

MODEL = "Qwen3-4B-Instruct-2507"
runs = run_day("2026-12-08")
price = PriceTable()
cost = {}                                   # Decimal money per message ID
for run in runs:
    cost[run.message.message_id] = sum((price.cost(MODEL, s.prompt_tokens, s.cached_tokens, s.completion_tokens,
                                                   s.start_ns)
                                        for s in run.outcome.steps if s.name == "chat"), Decimal(0))
ranked = sorted(runs, key=lambda run: (-cost[run.message.message_id], int(run.message.message_id)))
k = math.ceil(Fraction(1, 100) * len(runs))  # 1% of 200 is 2 messages
tail = ranked[:k]
total = sum(cost.values(), Decimal(0))
tail_money = sum((cost[run.message.message_id] for run in tail), Decimal(0))
print("messages:", fmt_int(len(runs)))
print("messages in the most expensive 1%:", fmt_int(k))
print(f"cost of the day, {price.version}:", fmt_usd(total))
print(f"cost of the most expensive 1%, {price.version}:", fmt_usd(tail_money))
print("share of the day's cost, most expensive 1%:", fmt_share(tail_money, total))
print("most expensive message, route:", tail[0].outcome.route)
print(f"most expensive message, cost, {price.version}:", fmt_usd(cost[tail[0].message.message_id]))
print("most expensive 1%, messages resolved by the model:", fmt_int(sum(run.outcome.source == "model" for run in tail)))
assert tail_money * len(runs) > total * k        # the tail costs more per message than the day does on average
```

Output:

```text
messages: 200
messages in the most expensive 1%: 2
cost of the day, book-2026-11-02: $0.007563
cost of the most expensive 1%, book-2026-11-02: $0.000234
share of the day's cost, most expensive 1%: 3.1%
most expensive message, route: messages
most expensive message, cost, book-2026-11-02: $0.000118
most expensive 1%, messages resolved by the model: 2
```

On this day there is no concentrated expensive tail. The two most expensive messages cost $0.000234 of the day's $0.007563, which is 3.1% of the cost. The most expensive of them, on the `messages` route, cost $0.000118. Both of the top two were resolved by the model, so [the tail](#tail-percentiles-with-intervals) is an answer tail, not a fallback one.

The count is exact over one day, so it says what this day's messages cost and nothing about another day. How far another day would move the share needs a method this chapter does not use. The method is the bootstrap, which applies to any per-message statistic, and [chapter 7](#tail-percentiles-with-intervals) introduces it. Until then, a tail on one day is a count to report with its denominator, and not a rate to plan a budget on.

**Working rule:** Report the top 1% of messages as a count and as a share of the day's total, with the day named. Do not call a share small or large until a second day gives something to compare it with.

## What goes wrong in production {#tokens-and-cost-in-production}

A token total on a dashboard can double after a gateway or a rollup starts carrying the usage of the calls beneath it, and nothing else in the pipeline changed. The sum over spans counts those tokens twice. Read totals from the counters, or filter the spans by operation name, as the conventions' note says.

A dashboard total read from spans halves when the backend starts keeping half its traces, because the spans fall with the sample. The counters are unaffected. Keep the counters for totals, and keep the spans for questions the counters cannot answer, such as which route a message took. [Chapter 11](#estimating-totals-from-a-sample) scales a sampled total up, with its error.

The bill moves while the input count stays flat, because a release changed how much of the prompt was cached. A dashboard that tracks input tokens alone misses the change. Track cost beside input and cached input, and read the cached count against the release it belongs to.

A local model is priced at a hosted provider's rates when a cost tool takes the provider from the span, and the span says `openai`. The listing fails loudly on that lookup, so the danger is a tool that falls back to a default model or a fuzzy match. The book's table is keyed by model, and a listing is queried with its provider named. Any tool that prices a span should do the same.

A month's cost changes on the day a price changes, though no message did. Each row in the book's table carries a valid-from date, and each call is priced at its own timestamp. A cost stored on a span would keep the old price, so the book computes cost at query time.

A budget set in English tokens fails for Hindi users, and the difference lies in the vocabulary, not in the traffic. Measure each locale's ratio on the traffic that will run, and count with the tokenizer that serves the locale.

**Working rule:** Keep totals on the counters, cost on the table with its version, and each locale's count on its own tokenizer. When a release changes the prompt or the cache, read its cost next to its tokens, because the two can move apart.

## What this chapter decided {#tokens-and-cost-decisions}

- Tokens come first and money second. Every money figure names the price table's version, `book-2026-11-02`, and its date.
- Input tokens include the cached part. Cached input is derived from the runtime's counters, and it is never added to input.
- Totals come from the counters. A sum over spans is taken over inference spans only, filtered by operation name. An agent span's usage is that agent's total, and it is never added to the calls' usage.
- Cost is computed at query time from the table and each call's timestamp. It is not stored on spans.
- The cache-off release is called reset per call, because the pinned runtime has no switch for the cache.
- Locale counts use the tokenizer file, after NFC normalisation, and the chapter prints no GGUF count. Utterance text is not quoted, because no example prints it.
- The chapter uses no interval, because a one-day count is exact and needs none. [Chapter 7](#tail-percentiles-with-intervals) gives the method for another day's spread.
- The prices are the book's judgement: dated, versioned and not a quote. A reader who prefers another price changes the table and keeps the counts, and every sentence about tokens still holds. That split is why the chapter does the tokens first.

# Find where the latency comes from

By the end of this chapter you can say which step sets a message's time, at the median and in the tail, and print each number with its count and an interval around it. Ambrewick's assistant answers each message in up to five steps, and its traces show every step of a message but not which step sets the message's end. On baseline day 1, the 200 messages this chapter reads, the median message took 8,099.3 ms, and the 95th percentile took 18,351.2 ms. Was that time spent reading articles, writing the reply, or waiting on a tool?

Every time here comes from one recording machine, a 4-vCPU Intel Xeon at 2.10 GHz that ran Qwen3-4B-Instruct-2507 (the 4B). Each time is either a call's recorded time or a sum of them on the virtual clock described in [Replay and the virtual clock](#replay-and-the-virtual-clock). A message's time here is the recorded time of each call it made, plus the modelled time of the in-process tools and the recorded time of the contacts calls, added up on that clock. The recorder also kept the time between calls, and the replay leaves it out. Over the whole day that time totals 651.4 ms, and each section says which of the two its numbers are.

The chapter builds the chain of calls that sets a message's end, the split of each model call into its reading and its writing, and then the tail, with a percentile and its interval for each route.

## The critical path sets the end time {#the-critical-path}

A message's trace is a tree of timed spans, and the root span ends when the reply goes out. Most spans sit inside the root, and most of them do not set that end. To find the ones that do, walk back from the root's end: take the child that ends last, then the child that ends last before that child starts, and keep going until the walk reaches the root's start. The critical path is the chain of spans that sets a message's end time; shortening any other span doesn't end the message sooner. Shorten a span on the chain and the message gets shorter, until another chain becomes the longer one.

Example `critical-path-one-message` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Replay the slowest message of baseline day 1 and list the chain of spans that sets its end time. The replay runs the
calls one after another, so every call is on the chain, and shortening any one of them shortens this message: the point
rests on the path lines and the assert that the path covers the whole message. The recorder's gaps between calls are
not in the replay; the day's total of them is printed beside it. The tool's time is modelled, a few microseconds, so it
prints as 0.0 ms."""
from lib.critical_path import critical_path
from lib.dayrun import DATA, run_day, run_day_traced
from lib.report import fmt_ms, fmt_share

import json

DAY = "2026-12-08"
runs = run_day(DAY)                                                      # all 200 messages, in arrival order
slowest = max(runs, key=lambda run: run.replied_ns - run.arrived_ns)     # the longest of the day; no other message ties with it
traced = run_day_traced(DAY, [slowest.message.message_id], live=False)   # its spans, replayed the same way
by_id = {row["span_id"]: row for row in traced.spans}
path = critical_path(traced.spans)                                       # root first, then the chain in time order
message = by_id[path[0]]
message_time = message["end_ns"] - message["start_ns"]
chain = [by_id[span_id] for span_id in path[1:]]
covered = sum(row["end_ns"] - row["start_ns"] for row in chain)

print("message:", slowest.message.message_id)
print("route:", slowest.outcome.route)
print("message time:", fmt_ms(message_time))
for number, row in enumerate(chain, start=1):
    # The inference spans carry their prompt's name, so the route call and the answer calls read apart.
    name = row["attributes"].get("gen_ai.prompt.name", row["name"])
    print(f"on the path, {number}: {name}, time: {fmt_ms(row['end_ns'] - row['start_ns'])}")
print("share of the message time on the path:", fmt_share(covered, message_time))

# The recorder's own offsets give the gaps the replay does not keep: each message's span minus its calls' times.
rows = [json.loads(line) for line in (DATA / "baseline-day-1" / "traces.jsonl").read_text(encoding="utf-8").splitlines()]
gap_ns = 0
for message_id in sorted({row["message_id"] for row in rows}):
    calls = [row for row in rows if row["message_id"] == message_id]
    span = max(c["offset_ns"] + c["total_ns"] for c in calls) - min(c["offset_ns"] for c in calls)
    gap_ns += span - sum(c["total_ns"] for c in calls)
print("gaps between calls, recorded, all messages of the day:", fmt_ms(gap_ns))

# A constructed tree, not the recording: two calls that overlap. The one that ends last sets the end, and the other
# is off the path, since the walk back from the end reaches the later call's start before it reaches the earlier one.
toy = [
    {"span_id": "a", "parent_span_id": None, "start_ns": 0, "end_ns": 10, "span_seq": 1},
    {"span_id": "b", "parent_span_id": "a", "start_ns": 0, "end_ns": 6, "span_seq": 2},
    {"span_id": "c", "parent_span_id": "a", "start_ns": 2, "end_ns": 9, "span_seq": 3},
]
toy_covered = sum(row["end_ns"] - row["start_ns"] for row in toy if row["span_id"] in critical_path(toy)[1:])
print("constructed overlap, span IDs on the path:", ", ".join(critical_path(toy)))
print("constructed overlap, share of the root's time on the path:", fmt_share(toy_covered, toy[0]["end_ns"] - toy[0]["start_ns"]))
assert critical_path(toy) == ["a", "c"]
assert covered == message_time                 # the chain's calls cover the whole message, with no gap
assert len(chain) == len(traced.spans) - 1     # every call of the message is on the path
```

Output:

```text
message: 7055
route: calendar
message time: 24,305.8 ms
on the path, 1: ambrewick.route, time: 1,666.5 ms
on the path, 2: ambrewick.answer, time: 14,993.5 ms
on the path, 3: execute_tool add_event, time: 0.0 ms
on the path, 4: ambrewick.answer, time: 7,645.8 ms
share of the message time on the path: 100.0%
gaps between calls, recorded, all messages of the day: 651.4 ms
constructed overlap, span IDs on the path: a, c
constructed overlap, share of the root's time on the path: 70.0%
```

This run replays message 7055, the longest message of the day, on the calendar route, with its spans kept. The walk gives four links: the route call, an answer call, the `add_event` tool and a second answer call. The output gives each one's time, and the four add up to the message's 24,305.8 ms. The share of that time on the path is 100.0%, and the run asserts that the chain covers the whole message.

A replay can show that share because its calls run one after another, with nothing between them. The recorder's gaps have no span of their own, so a path built from spans would leave them off, and this message's replay has none of the day's gaps. The path covers the model calls, the modelled time of the in-process tools and the recorded time of the contacts calls, and nothing else. The retrieve step gets no time either, since its span starts and ends at one instant.

Overlap is the case a replay cannot show. No recorded message has two calls running at once, so the run builds a small tree by hand. Span a is the root and ends at 10. Span b runs from 0 to 6, and span c from 2 to 9. The walk from the end reaches c first and never returns to b, so the path is a, c. Span b is off the path, and shortening b does not move the end. That holds on this tree only. The path covers 70.0% of the root's time, so the spans on it explain only that much of the time. That is the low share the working rule warns of.

**Working rule:** Walk the critical path before you tune a trace, and change only the spans on it. Read the path's share of the message time first. A low share means the spans you have do not explain the time, and the rest belongs to no span. A replay's path always covers its message, so a replay cannot tell you which of two overlapping calls matters.

## Time to first chunk {#time-to-first-chunk}

The answer calls hold most of the path, so the next question is where inside a call the time goes. Time to first chunk is the time from sending a model call to receiving the first streamed piece of its reply. The conventions at tag 0.1.0 measure that wait with the metric `gen_ai.client.inference.time_to_first_chunk`, which is a [histogram](#totals-from-metrics-not-spans) in seconds, on streaming calls only and only when a chunk arrives. The span attribute `gen_ai.response.time_to_first_chunk` measures from the start of the logical operation, before authentication and the first attempt, so a hosted client's [retries](#retries-under-a-timeout) count toward it. [Chapter 3's name table](#hand-made-against-instrumented) maps the package's name for the metric to the standard's.

The numbers in this section come from the recorder, not from the metric, which these examples do not run. The recorder timed the first stream event of each streamed reply, which this runtime sends together with the first content. A local model has no authentication step to add.

Each median in this section comes with a 95% interval, which [tail percentiles with intervals](#tail-percentiles-with-intervals) defines.

Example `time-to-first-chunk-by-route` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Take each message's last answer call on baseline day 1, the one that writes the reply the user reads, and compare its time
to first chunk with its total time, by route. Fallback replies make no answer call, so they have no first chunk, and each
interval resamples messages, not calls (PL-6)."""

from lib.dayrun import DATA, run_day
from lib.report import fmt_int, fmt_ms, fmt_share
from lib.stats import bootstrap_interval, nearest_rank

import json
from collections import defaultdict

runs = run_day("2026-12-08")
routes = {run.message.message_id: run.outcome.route for run in runs}
rows = [json.loads(line) for line in (DATA / "baseline-day-1" / "traces.jsonl").read_text(encoding="utf-8").splitlines()]
# A first chunk comes before the call ends, and the recorder keeps both times for every call.
assert all(row["ttfc_ns"] <= row["total_ns"] for row in rows)
last_answer = {}
for row in sorted(rows, key=lambda r: r["seq"]):          # the sequence numbers give the order the calls were made
    if row["step"] == "answer":
        last_answer[row["message_id"]] = row               # the later call overwrites the earlier one
by_route = defaultdict(list)
for message_id, row in last_answer.items():
    by_route[routes[message_id]].append(row)
assert not any(routes[message_id] == "fallback" for message_id in last_answer)

print("interval method: bootstrap over messages, 2,000 resamples, seed 20261207, 95%")
for route in sorted(by_route):
    calls = by_route[route]
    ttfc = [call["ttfc_ns"] for call in calls]
    total = [call["total_ns"] for call in calls]
    low, high = bootstrap_interval(calls, lambda units: nearest_rank([u["ttfc_ns"] for u in units], 50))
    print(f"{route}, messages with an answer call: {fmt_int(len(calls))}")
    print(f"{route}, time to first chunk, median: {fmt_ms(nearest_rank(ttfc, 50))}")
    print(f"{route}, time to first chunk, 95% interval: {fmt_ms(low)} to {fmt_ms(high)}")
    print(f"{route}, total time of the answer call, median: {fmt_ms(nearest_rank(total, 50))}")
    print(f"{route}, time to first chunk, share of the call's time: {fmt_share(sum(ttfc), sum(total))}")

route_calls = [row for row in rows if row["step"] == "route"]
print("route calls, time to first chunk, median, all messages:", fmt_ms(nearest_rank([c["ttfc_ns"] for c in route_calls], 50)))
print("route calls, n:", fmt_int(len(route_calls)))
print("messages with no answer call:", fmt_int(len(runs) - len(last_answer)))
```

Output:

```text
interval method: bootstrap over messages, 2,000 resamples, seed 20261207, 95%
alarms, messages with an answer call: 16
alarms, time to first chunk, median: 5,985.6 ms
alarms, time to first chunk, 95% interval: 1,514.8 ms to 6,456.4 ms
alarms, total time of the answer call, median: 9,744.4 ms
alarms, time to first chunk, share of the call's time: 49.6%
calendar, messages with an answer call: 27
calendar, time to first chunk, median: 6,818.8 ms
calendar, time to first chunk, 95% interval: 1,120.5 ms to 7,322.9 ms
calendar, total time of the answer call, median: 10,676.0 ms
calendar, time to first chunk, share of the call's time: 48.8%
devices, messages with an answer call: 17
devices, time to first chunk, median: 6,090.0 ms
devices, time to first chunk, 95% interval: 4,377.7 ms to 6,616.4 ms
devices, total time of the answer call, median: 11,326.7 ms
devices, time to first chunk, share of the call's time: 47.7%
lists, messages with an answer call: 13
lists, time to first chunk, median: 8,563.7 ms
lists, time to first chunk, 95% interval: 8,397.1 ms to 8,866.0 ms
lists, total time of the answer call, median: 12,256.8 ms
lists, time to first chunk, share of the call's time: 69.5%
media, messages with an answer call: 31
media, time to first chunk, median: 5,911.4 ms
media, time to first chunk, 95% interval: 5,663.0 ms to 6,128.4 ms
media, total time of the answer call, median: 11,073.2 ms
media, time to first chunk, share of the call's time: 49.8%
messages, messages with an answer call: 7
messages, time to first chunk, median: 9,289.0 ms
messages, time to first chunk, 95% interval: 485.7 ms to 12,842.8 ms
messages, total time of the answer call, median: 13,865.7 ms
messages, time to first chunk, share of the call's time: 59.4%
route calls, time to first chunk, median, all messages: 530.2 ms
route calls, n: 200
messages with no answer call: 89
```

The output takes each message's last answer call, the one that writes the reply the user reads, and sets its time to first chunk beside its total time, by route. Messages routed to the fallback reply make no answer call, which [chapter 1](#where-the-time-went-in-twenty-messages) describes, so the output counts them apart: 89 of them. The 200 route calls, which pick a route, reach their first chunk at a median of 530.2 ms.

Answer calls take longer to produce that first chunk. Leaving aside the messages route, which has 7, lists has the largest median first chunk, 8,563.7 ms, from 13 messages. Its 95% interval, 8,397.1 ms to 8,866.0 ms, sits above every other route's but messages'.

On lists, the first chunk takes 69.5% of the call's time. On the other routes that share runs from 47.7% to 59.4%.

The messages route needs the most care. Its median first chunk is 9,289.0 ms, from 7 messages, and its 95% interval, 485.7 ms to 12,842.8 ms, is the widest in the output.

**Working rule:** Print time to first chunk beside the total time of the same call, and read the two together. An early first chunk means the user sees output early. It does not mean the call was cheap. Compare routes on their intervals and on the share, and do not name a route's first chunk from a handful of messages.

## Prefill against generation {#prefill-against-generation}

The first chunk waits on the prompt, so the next question is how much of that wait is reading the prompt and how much is something else. Prefill is the model reading the prompt; generation is it writing the reply, one token at a time. Serving papers for GPUs make the same split: prefill keeps the compute busy, and each decoding step leaves most of it idle ([Agrawal et al., Sarathi-Serve](https://www.usenix.org/conference/osdi24/presentation/agrawal), OSDI 2024; [Yu et al., Orca](https://www.usenix.org/conference/osdi22/presentation/yu), OSDI 2022, for one output token per iteration).

The counts in this section need no new definition. [Chapter 6](#three-token-counts) says where input and output tokens come from, and [its cached-input section](#cached-prompt-tokens) says how the cached share is derived. The tokens evaluated are what remains of the input once the cached prefix is taken away, which is the input the model actually read.

The counters come from llama-cpp-python, which exposes llama.cpp's counters for each context: the prompt tokens evaluated and the time they took, and the tokens generated and the time they took. The counters only add up, so the recorder takes the difference before and after each call. Its four warm-up calls, made before each process's first recorded message, are outside the split.

Example `prefill-generation-split` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Split the recorded compute of each model call on baseline day 1 into prefill (the prompt the model read) and generation
(the tokens it wrote), from llama.cpp's counters on the recording machine. The split is the method's output: the numbers
belong to that machine, and the method carries to other hardware. The recorder's warm-up call, made before each
process's first recorded message, is not recorded, so it is not in the split. Rates are computed from the recorded counts."""

from lib.dayrun import DATA
from lib.report import fmt_int, fmt_share

import json

rows = [json.loads(line) for line in (DATA / "baseline-day-1" / "traces.jsonl").read_text(encoding="utf-8").splitlines()]
for step in ("route", "answer"):
    calls = [row for row in rows if row["step"] == step]
    prefill = sum(call["prefill_ns"] for call in calls)
    generation = sum(call["gen_ns"] for call in calls)
    first_chunk = sum(call["ttfc_ns"] for call in calls)
    evaluated = sum(call["tokens_evaluated"] for call in calls)   # the prompt's tokens the model read, minus cached ones
    written = sum(call["completion_tokens"] for call in calls)
    assert all(call["prefill_ns"] <= call["ttfc_ns"] for call in calls)   # the first chunk waits for the prompt
    print(f"{step} calls: {fmt_int(len(calls))}")
    print(f"{step}, prefill share of prefill plus generation: {fmt_share(prefill, prefill + generation)}")
    print(f"{step}, prefill share of time to first chunk: {fmt_share(prefill, first_chunk)}")
    print(f"{step}, prompt tokens evaluated per second of prefill, computed: {evaluated * 1e9 / prefill:.1f}")
    print(f"{step}, tokens written per second of generation, computed: {written * 1e9 / generation:.1f}")
```

Output:

```text
route calls: 200
route, prefill share of prefill plus generation: 32.8%
route, prefill share of time to first chunk: 72.7%
route, prompt tokens evaluated per second of prefill, computed: 47.6
route, tokens written per second of generation, computed: 7.3
answer calls: 121
answer, prefill share of prefill plus generation: 54.1%
answer, prefill share of time to first chunk: 91.2%
answer, prompt tokens evaluated per second of prefill, computed: 62.3
answer, tokens written per second of generation, computed: 7.0
```

The output splits each step's compute into the two kinds of work, route calls first. The route calls read a fixed instruction and the message, and the answer calls read the message and whatever the route fetched. A route call's first chunk waits for its prompt: prefill is 72.7% of that wait, though only 32.8% of the call's compute. The answer calls wait on the same thing in larger measure. Prefill is 91.2% of their wait for the first chunk, so the first word of a reply is mostly the prompt being read.

Generation on the answer calls runs at 7.0 tokens a second, and prefill reads 62.3 tokens evaluated a second. Those rates are computed from the counts and hold for this machine, for the reason that [Small Open Models](https://rollingedition.com/small-open-models/s/measure-speed-in-a-recording) gives: a small model's speed is measured in a recording on one named machine and never quoted as a rule. Prefill is counted in tokens evaluated, not in input tokens, and the [next section](#retrieved-context-against-prefill) shows why that choice matters.

**Working rule:** Split a model call's time into prefill and generation before you change its prompt or its reply length. Take the split from the counters, on the same machine and the same calls, and read it beside the total. When prefill is most of the time to first chunk, the prompt is where the wait is. When generation is most of the call, the reply's length is.

## Retrieved context against prefill {#retrieved-context-against-prefill}

Retrieval puts articles into the answer call's prompt, so a release that retrieves more should make prefill longer. The question for that release is how much longer, and whether the model reads all of the added input. The top-8 release gives the answer call up to eight articles, where the baseline gives up to three, on the routes that retrieve. Route calls come before retrieval, so their prompts hold no articles in either release.

The comparison uses the same messages under both releases, the paired 60: the messages of baseline day 1 that the top-8 release was also recorded on. The output's r0 is the baseline and r3 is the top-8 release. It sums each release's answer calls over those messages, and that is a sum, not a comparison with an interval. Chapter 10 pairs the same messages and gives the interval on the difference.

Example `context-against-prefill` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Compare the same 60 messages under r0 (the baseline, on baseline day 1) and r3 (the top-8 release): the answer calls'
prefill, tokens and cache, and the route calls' cache. More articles make the prompt longer, and prefill follows the tokens the
model had to evaluate, since a cached prefix is not read again while the cache holds it. The correlations are over all of
baseline day 1's answer calls, computed; the paired interval belongs to chapter 10, so none is printed here."""

from lib.case import load_messages
from lib.dayrun import DATA
from lib.report import fmt_int, fmt_ms

import json
from collections import Counter
from statistics import correlation


def load(folder):
    return [json.loads(line) for line in (DATA / folder / "traces.jsonl").read_text(encoding="utf-8").splitlines()]


def total(rows, step, field):
    return sum(row[field] for row in rows if row["step"] == step)


paired = {message.message_id for message in load_messages("2026-12-08-paired")}   # the 60 messages, same arrivals
base = load("baseline-day-1")
releases = {"r0": [row for row in base if row["message_id"] in paired], "r3": load("release-top-8")}
assert {row["message_id"] for row in releases["r3"]} == paired     # r3 was recorded for exactly these messages
for name, rows in releases.items():
    print(f"{name}, prefill summed over the answer calls:", fmt_ms(total(rows, "answer", "prefill_ns")))
    print(f"{name}, prompt tokens summed over the answer calls:", fmt_int(total(rows, "answer", "prompt_tokens")))
    print(f"{name}, prompt tokens evaluated summed over the answer calls:", fmt_int(total(rows, "answer", "tokens_evaluated")))
    print(f"{name}, cached prompt tokens summed over the answer calls:", fmt_int(total(rows, "answer", "cached_tokens_derived")))
    print(f"{name}, prompt tokens evaluated summed over the route calls:", fmt_int(total(rows, "route", "tokens_evaluated")))
print("prefill, r3 over r0, computed:", f"{total(releases['r3'], 'answer', 'prefill_ns') / total(releases['r0'], 'answer', 'prefill_ns'):.2f}")

# The same answer calls under both releases: sorted by message, then by call, so each pair is one message's n-th answer.
before = sorted((row for row in releases["r0"] if row["step"] == "answer"), key=lambda row: (row["message_id"], row["seq"]))
after = sorted((row for row in releases["r3"] if row["step"] == "answer"), key=lambda row: (row["message_id"], row["seq"]))
assert all(b["message_id"] == a["message_id"] and b["prompt_tokens"] <= a["prompt_tokens"] for b, a in zip(before, after))
gained = sum(a["prompt_tokens"] > b["prompt_tokens"] for b, a in zip(before, after))   # the assert: none loses any
print("paired answer calls, r3 with more prompt tokens than r0:", f"{gained} of {len(before)}")

route = {name: {row["message_id"]: row for row in rows if row["step"] == "route"} for name, rows in releases.items()}
assert all(route["r0"][m]["input_key"] == route["r3"][m]["input_key"]
           and route["r0"][m]["prompt_tokens"] == route["r3"][m]["prompt_tokens"] for m in paired)   # identical route prompts
cached = {name: [row["cached_tokens_derived"] for row in rows if row["step"] == "route"] for name, rows in releases.items()}
instruction = Counter(cached["r0"]).most_common(1)[0][0]        # the cached count most route calls get: the instruction
print("route instruction, cached tokens in most route calls:", fmt_int(instruction))
for name in releases:
    print(f"{name}, route calls that re-read most of the instruction:", sum(c < instruction for c in cached[name]))

answer_calls = [row for row in base if row["step"] == "answer"]
by_prompt = correlation([row["prompt_tokens"] for row in answer_calls], [row["prefill_ns"] for row in answer_calls])
by_evaluated = correlation([row["tokens_evaluated"] for row in answer_calls], [row["prefill_ns"] for row in answer_calls])
print("prefill against prompt tokens, correlation, computed:", f"{by_prompt:.2f}")
print("prefill against tokens evaluated, correlation, computed:", f"{by_evaluated:.2f}")
assert by_evaluated > 0.9 and by_evaluated > by_prompt   # the cached prefix adds to the prompt, not to the prefill
```

Output:

```text
r0, prefill summed over the answer calls: 172,043.5 ms
r0, prompt tokens summed over the answer calls: 20,420
r0, prompt tokens evaluated summed over the answer calls: 10,855
r0, cached prompt tokens summed over the answer calls: 9,565
r0, prompt tokens evaluated summed over the route calls: 827
r3, prefill summed over the answer calls: 289,244.2 ms
r3, prompt tokens summed over the answer calls: 27,326
r3, prompt tokens evaluated summed over the answer calls: 17,813
r3, cached prompt tokens summed over the answer calls: 9,513
r3, prompt tokens evaluated summed over the route calls: 1,209
prefill, r3 over r0, computed: 1.68
paired answer calls, r3 with more prompt tokens than r0: 15 of 33
route instruction, cached tokens in most route calls: 133
r0, route calls that re-read most of the instruction: 1
r3, route calls that re-read most of the instruction: 4
prefill against prompt tokens, correlation, computed: 0.29
prefill against tokens evaluated, correlation, computed: 0.99
```

On the paired messages, the answer calls take 289,244.2 ms of prefill under the top-8 release, against 172,043.5 ms under the baseline: 1.68 times as much. The output also gives two correlations over every answer call of baseline day 1.

The input grows with the articles. Input tokens rise from 20,420 to 27,326, and tokens evaluated, the input the model read, rise from 10,855 to 17,813.

Both releases skip about the same cached prefix, 9,565 tokens under the baseline and 9,513 under the top-8 release, so the model reads the added input. Under the top-8 release, 15 of 33 paired answer calls gained prompt tokens, and none lost any.

The route calls show a gap without any article in their prompts. Under the top-8 release they evaluate 1,209 tokens, against 827 under the baseline, on prompts the example asserts are identical under both releases.

The cause is the recorder's cache. The cache is bounded at 1 GiB and drops its oldest state first, so a route call that runs after enough others finds its instruction gone and reads it again. The recording logs no cache hits, so this follows from the cache's rule and not from a log. The cache holds the instruction, 133 tokens, for most route calls. Under the top-8 release, 4 route calls re-read most of it, against 1 under the baseline.

Prefill follows tokens evaluated rather than input. Across baseline day 1's answer calls, prefill correlates 0.99 with tokens evaluated and 0.29 with input. A prefix the model has read before is not read again while the cache holds it, so input can grow while the work does not, and the tokens a call evaluates depend on the calls before it.

**Working rule:** Measure a prompt's extra prefill on the same messages as the release it changes, and read tokens evaluated beside input tokens. Input tokens say how large the prompt is. Tokens evaluated say how much work the model did, and when a prefix is cached the two counts part company. Act on the work.

## Tail percentiles with intervals {#tail-percentiles-with-intervals}

The medians so far leave out the messages that wait longest, and those are the ones a tail percentile is for. This book uses the nearest rank. The p-th percentile is the value at sorted position ceil(p/100 × n); the tail is the slowest few percent of messages. Sort the n values, count to position ceil(p/100 × n), and take the value there. It always returns a message that occurred.

[Chapter 1](#whats-rough) said that twenty messages cannot support a tail percentile. Two hundred can, with an interval beside it, and every percentile in this chapter states its count, n. A percentile of seven messages is a different kind of number from one of 200, and the output shows which.

The rule has a consequence at the top of the list. On 200 values the 99th percentile is the value at position 198, which is the third largest, not the second. The output prints the rule on the values 1 to 200 so that the position is visible.

Predict before you run it. How many messages does a route need before its 95th percentile is anything but its slowest message? Work it from ceil(0.95 × n), then check the output.

Example `percentiles-by-route` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Print each route's median, p95 and p99 of message time on baseline day 1, every one with its message count n, and a 95%
interval on each p95. Percentiles are nearest rank: the value at position ceil(p/100 x n). The interval is a bootstrap over
messages, 2,000 resamples, seed 20261207. A route with fewer than 20 messages has its p95 at its largest message, which the
example prints and asserts."""

from lib.dayrun import run_day
from lib.report import fmt_int, fmt_ms
from lib.stats import bootstrap_interval, nearest_rank

from collections import defaultdict

runs = run_day("2026-12-08")
by_route = defaultdict(list)
for run in runs:
    by_route[run.outcome.route].append(run.replied_ns - run.arrived_ns)   # the message's time on the virtual clock
times = [run.replied_ns - run.arrived_ns for run in runs]
groups = {"all routes": times, **by_route}
intervals = {}
print("interval method: bootstrap over messages, 2,000 resamples, seed 20261207, 95%")
print("p99 of the values 1 to 200 (n = 200), nearest rank:", nearest_rank(list(range(1, 201)), 99))
assert nearest_rank(list(range(1, 201)), 99) == 198   # the 198th value, the third largest of 200
print("fewest values before the p95 is not the largest, nearest rank:",
      next(n for n in range(1, 201) if nearest_rank(list(range(1, n + 1)), 95) != n))
for name in ["all routes"] + sorted(by_route):
    values = groups[name]
    low, high = bootstrap_interval(values, lambda units: nearest_rank(units, 95))
    intervals[name] = (low, high)
    print(f"{name}, messages (n): {fmt_int(len(values))}")
    print(f"{name}, median: {fmt_ms(nearest_rank(values, 50))}")
    print(f"{name}, p95: {fmt_ms(nearest_rank(values, 95))}")
    print(f"{name}, p95, 95% interval: {fmt_ms(low)} to {fmt_ms(high)}")
    print(f"{name}, p99: {fmt_ms(nearest_rank(values, 99))}")
small = [name for name in sorted(by_route) if len(by_route[name]) < 20]
print("routes under 20 messages, count:", len(small))
print("routes under 20 messages, p95 is their largest message:", ", ".join(small))
for name in small:
    assert nearest_rank(by_route[name], 95) == max(by_route[name])   # ceil(0.95 n) = n for every n up to 19
assert len(times) == len(runs) == 200
# Two routes' p95 intervals overlap, so the largest p95 cannot be told apart from the next one with this many messages.
low_m, high_m = intervals["messages"]
low_c, high_c = intervals["calendar"]
assert low_m <= high_c and low_c <= high_m
```

Output:

```text
interval method: bootstrap over messages, 2,000 resamples, seed 20261207, 95%
p99 of the values 1 to 200 (n = 200), nearest rank: 198
fewest values before the p95 is not the largest, nearest rank: 20
all routes, messages (n): 200
all routes, median: 8,099.3 ms
all routes, p95: 18,351.2 ms
all routes, p95, 95% interval: 16,452.7 ms to 20,909.8 ms
all routes, p99: 22,425.7 ms
alarms, messages (n): 16
alarms, median: 12,159.5 ms
alarms, p95: 22,425.7 ms
alarms, p95, 95% interval: 15,757.0 ms to 22,425.7 ms
alarms, p99: 22,425.7 ms
calendar, messages (n): 27
calendar, median: 12,519.8 ms
calendar, p95: 20,909.8 ms
calendar, p95, 95% interval: 14,623.8 ms to 24,305.8 ms
calendar, p99: 24,305.8 ms
devices, messages (n): 17
devices, median: 12,510.2 ms
devices, p95: 17,417.9 ms
devices, p95, 95% interval: 14,532.9 ms to 17,417.9 ms
devices, p99: 17,417.9 ms
fallback, messages (n): 89
fallback, median: 1,392.0 ms
fallback, p95: 1,726.6 ms
fallback, p95, 95% interval: 1,636.7 ms to 3,108.1 ms
fallback, p99: 3,191.4 ms
lists, messages (n): 13
lists, median: 13,786.6 ms
lists, p95: 17,183.7 ms
lists, p95, 95% interval: 14,842.4 ms to 17,183.7 ms
lists, p99: 17,183.7 ms
media, messages (n): 31
media, median: 12,708.9 ms
media, p95: 16,452.7 ms
media, p95, 95% interval: 14,786.5 ms to 18,351.2 ms
media, p99: 18,351.2 ms
messages, messages (n): 7
messages, median: 19,793.3 ms
messages, p95: 24,253.7 ms
messages, p95, 95% interval: 21,244.6 ms to 24,253.7 ms
messages, p99: 24,253.7 ms
routes under 20 messages, count: 4
routes under 20 messages, p95 is their largest message: alarms, devices, lists, messages
```

The output gives each route's median, 95th and 99th percentile, each with its count, and a 95% interval on each 95th percentile. A route needs at least 20 messages before its 95th percentile is anything but its largest. 4 routes have fewer than 20 messages, alarms, devices, lists, messages, and for each one the 95th percentile is its slowest message.

The messages route's 95th percentile is 24,253.7 ms from 7 messages, with a 95% interval of 21,244.6 ms to 24,253.7 ms whose top is the same value. Its last answer calls are the longest of the answering routes at the median, at 13,865.7 ms. The output does not say why its tail is long.

The all-routes median, 8,099.3 ms, is lower than the median of every route that answered. The reason is the fallback route. 89 of the 200 messages took the fallback reply, which makes one route call and no answer call, and their median is 1,392.0 ms. The all-routes median is the middle value of all the messages, so those messages pull it down.

Example `figure-latency-tail-by-route` (Python 3.13.16 · bm25s 0.3.16 · matplotlib 3.11.2 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Draw each route's median and p95 of message time on baseline day 1, with a 95% interval on the p95, so the tail's place
in each route shows at a glance. Every value the figure draws is printed first, with its message count n. The interval
is a bootstrap over messages (2,000 resamples, seed 20261207); the route is the one the assistant chose."""

from lib.dayrun import run_day
from lib.figures import ACCENT, INK, MUTED, new_figure, save
from lib.report import fmt_int, fmt_ms
from lib.stats import bootstrap_interval, nearest_rank

from collections import defaultdict

runs = run_day("2026-12-08")
times = {"all routes": [run.replied_ns - run.arrived_ns for run in runs]}
for run in runs:
    times.setdefault(run.outcome.route, []).append(run.replied_ns - run.arrived_ns)
names = ["all routes"] + sorted(name for name in times if name != "all routes")
summary = []
for name in names:
    values = times[name]
    low, high = bootstrap_interval(values, lambda units: nearest_rank(units, 95))
    summary.append((name, len(values), nearest_rank(values, 50), nearest_rank(values, 95), low, high))
    print(f"{name}, messages (n): {fmt_int(len(values))}")
    print(f"{name}, median: {fmt_ms(summary[-1][2])}")
    print(f"{name}, p95: {fmt_ms(summary[-1][3])}, interval: {fmt_ms(low)} to {fmt_ms(high)}")

fig, ax = new_figure(height=3.8)
rows = list(range(len(summary)))[::-1]                 # the first row, all routes, at the top
for row, (name, count, median, p95, low, high) in zip(rows, summary):
    ax.hlines(row, low / 1e6, high / 1e6, color=MUTED, linewidth=3, label="95% interval of the p95" if row == rows[0] else None)
    ax.scatter([median / 1e6], [row], facecolors="none", edgecolors=INK, linewidths=1.4, s=52, zorder=3,
               label="median" if row == rows[0] else None)     # a hollow circle, so the two dots differ in shape as well as colour
    ax.scatter([p95 / 1e6], [row], color=ACCENT, marker="D", s=44, zorder=3, label="p95" if row == rows[0] else None)
ax.set_yticks(rows, [f"{name} (n = {count})" for name, count, *_ in summary])
ax.set_xlabel("message time, milliseconds")
ax.set_xlim(0, 30000)
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.22), ncol=3)   # below the axis, clear of every row
save(fig, "latency-tail-by-route")
```

Output:

```text
all routes, messages (n): 200
all routes, median: 8,099.3 ms
all routes, p95: 18,351.2 ms, interval: 16,452.7 ms to 20,909.8 ms
alarms, messages (n): 16
alarms, median: 12,159.5 ms
alarms, p95: 22,425.7 ms, interval: 15,757.0 ms to 22,425.7 ms
calendar, messages (n): 27
calendar, median: 12,519.8 ms
calendar, p95: 20,909.8 ms, interval: 14,623.8 ms to 24,305.8 ms
devices, messages (n): 17
devices, median: 12,510.2 ms
devices, p95: 17,417.9 ms, interval: 14,532.9 ms to 17,417.9 ms
fallback, messages (n): 89
fallback, median: 1,392.0 ms
fallback, p95: 1,726.6 ms, interval: 1,636.7 ms to 3,108.1 ms
lists, messages (n): 13
lists, median: 13,786.6 ms
lists, p95: 17,183.7 ms, interval: 14,842.4 ms to 17,183.7 ms
media, messages (n): 31
media, median: 12,708.9 ms
media, p95: 16,452.7 ms, interval: 14,786.5 ms to 18,351.2 ms
messages, messages (n): 7
messages, median: 19,793.3 ms
messages, p95: 24,253.7 ms, interval: 21,244.6 ms to 24,253.7 ms
figure: figures/latency-tail-by-route.svg
```

*Figure 7.1. Each route's median and 95th percentile of message time on baseline day 1, with a 95% interval on the 95th percentile.*

![The answering routes' 95th percentiles have mostly overlapping intervals, and the fallback route's is far shorter](https://rollingedition.ai/books/observability-for-llm-applications/2026.11.2/figures/latency-tail-by-route.svg)

Figure 7.1 draws each route's median and 95th percentile, with the interval on the 95th percentile as a bar. The top row is all routes together. Read the answering routes' bars against one another. Most of their intervals overlap, and the messages interval overlaps calendar's, as the example asserts. The 4 routes under 20 messages have bars that end at their own largest message. The fallback bar is far shorter than the rest. So the tail depends on whether the route answers, and the count decides how sure the reader can be of where a route's tail sits.

The interval is a percentile bootstrap, and this is the one place the chapter builds it. An interval says how far a number would move had the day brought other messages drawn the same way; here, the middle 95% of 2,000 bootstrap resamples of messages. The question behind it is whether another day's 95th percentile would be the same. The interval answers that only for a day drawn the same way. A different day, a release or a load lies outside what it covers.

For each route, the code draws as many messages as the route has, with replacement, takes the 95th percentile of that resample, and repeats the draw 2,000 times with the seed 20261207. The interval is the 50th and the 1,950th of the 2,000 results, which bracket 95% of them. [Efron](https://doi.org/10.1214/aos/1176344552) introduced the bootstrap in 1979, and [Evaluating LLM Applications](https://rollingedition.com/evaluating-llm-applications/s/bootstrap-over-items) uses the same method over items. Here the unit is the message, not the span, because the spans of one message are not independent of one another.

The same bootstrap applies to any statistic taken per message, such as the share of the day's cost that the most expensive messages carry in [chapter 6](#the-expensive-tail). Under 20 messages, though, the 95th percentile of every resample is one of the route's own messages, and the largest of them is the top of the interval. The interval cannot reach past the messages it came from. So for each of the 4 routes under 20 messages, the upper end is its own largest message, the upper end and the point estimate are one value, and the interval's width measures the resampling, not what those few messages leave out.

**Working rule:** Print each percentile with its count and its interval, and rank two routes only when their intervals do not overlap. Collect more messages before you name a tail.

## Histogram buckets and what they hide {#histogram-buckets-and-what-they-hide}

A histogram keeps no messages, only counts. A bucket counts the values between two edges, so a percentile read from buckets is known only to within its bucket. The GenAI conventions at tag 0.1.0 say the boundaries SHOULD be these, in seconds, for their duration histograms, the agent's `gen_ai.client.invoke_agent.duration` included. The book uses them for message time, the duration this chapter measures: 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 81.92. A service exports the edges its configuration sets, which may not be these.

Example `bucket-edges-hide-tail` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Count baseline day 1's message times into the buckets the GenAI conventions advise for the agent's duration histogram, then
estimate the p95 from the bucket counts and set it beside the nearest-rank p95 of the raw values. The estimate spreads each
bucket's values evenly across it, and the p95 falls in one bucket, so the buckets can only place the estimate inside it."""

from lib import genai
from lib.dayrun import run_day
from lib.report import fmt_int, fmt_ms, fmt_share
from lib.stats import bucket_counts, nearest_rank

import math

EDGES_S = genai.BUCKETS["gen_ai.client.invoke_agent.duration"]   # the conventions' advised upper bounds, in seconds
print("GenAI conventions version:", genai.REGISTRY_VERSION)
print("bucket boundaries, GenAI conventions, seconds:", ", ".join(str(edge) for edge in EDGES_S))
runs = run_day("2026-12-08")
times = [run.replied_ns - run.arrived_ns for run in runs]
n = len(times)
edges = [round(edge * 1_000_000_000) for edge in EDGES_S]      # integer nanoseconds, as every time here is
counts = bucket_counts(times, edges)                           # a value sits in the bucket whose upper edge it does not exceed
print("messages (n):", fmt_int(n))
for index, count in enumerate(counts):
    low = edges[index - 1] if index else 0                     # a bucket starts at the upper edge of the one before it
    if index < len(edges):
        print(f"bucket above {fmt_ms(low)} up to {fmt_ms(edges[index])}: {fmt_int(count)} messages, {fmt_share(count, n)}")
    else:
        print(f"bucket above {fmt_ms(low)}: {fmt_int(count)} messages, {fmt_share(count, n)}")

exact = nearest_rank(times, 95)
rank = math.ceil(95 * n / 100)                                 # the nearest-rank position of the p95
index = next(i for i, edge in enumerate(edges) if exact <= edge)   # the bucket that holds the exact p95
low = edges[index - 1] if index else 0                         # its lower edge, as above; the first starts at zero
below = sum(counts[:index])                                    # messages in the buckets under it
estimate = low + round((rank - below) * (edges[index] - low) / counts[index])
print("bucket holding the p95, lower edge:", fmt_ms(low))
print("bucket holding the p95, upper edge:", fmt_ms(edges[index]))
print("messages in that bucket:", fmt_int(counts[index]))
print("messages at or below its lower edge:", fmt_int(below))
print("p95, nearest rank of the raw values:", fmt_ms(exact))
print("p95, estimated from the bucket counts:", fmt_ms(estimate))
print("estimate minus the nearest-rank p95:", fmt_ms(estimate - exact))
assert low < exact <= edges[index]                             # the exact p95 lies in the bucket that holds it
assert abs(estimate - exact) > 500_000_000                     # the bucket estimate is more than half a second off
```

Output:

```text
GenAI conventions version: 0.1.0
bucket boundaries, GenAI conventions, seconds: 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 81.92
messages (n): 200
bucket above 0.0 ms up to 10.0 ms: 0 messages, 0.0%
bucket above 10.0 ms up to 20.0 ms: 0 messages, 0.0%
bucket above 20.0 ms up to 40.0 ms: 0 messages, 0.0%
bucket above 40.0 ms up to 80.0 ms: 0 messages, 0.0%
bucket above 80.0 ms up to 160.0 ms: 0 messages, 0.0%
bucket above 160.0 ms up to 320.0 ms: 0 messages, 0.0%
bucket above 320.0 ms up to 640.0 ms: 0 messages, 0.0%
bucket above 640.0 ms up to 1,280.0 ms: 21 messages, 10.5%
bucket above 1,280.0 ms up to 2,560.0 ms: 65 messages, 32.5%
bucket above 2,560.0 ms up to 5,120.0 ms: 3 messages, 1.5%
bucket above 5,120.0 ms up to 10,240.0 ms: 16 messages, 8.0%
bucket above 10,240.0 ms up to 20,480.0 ms: 89 messages, 44.5%
bucket above 20,480.0 ms up to 40,960.0 ms: 6 messages, 3.0%
bucket above 40,960.0 ms up to 81,920.0 ms: 0 messages, 0.0%
bucket above 81,920.0 ms: 0 messages, 0.0%
bucket holding the p95, lower edge: 10,240.0 ms
bucket holding the p95, upper edge: 20,480.0 ms
messages in that bucket: 89
messages at or below its lower edge: 105
p95, nearest rank of the raw values: 18,351.2 ms
p95, estimated from the bucket counts: 20,019.8 ms
estimate minus the nearest-rank p95: 1,668.6 ms
```

The output counts the same messages of baseline day 1 into those buckets, estimates the 95th percentile from the counts, and sets the estimate beside the nearest-rank value of the raw messages. The bucket holding the 95th percentile runs from 10,240.0 ms to 20,480.0 ms. It holds 89 messages, and 105 messages sit at or below its lower edge.

The buckets place the 95th percentile between those edges, and no closer. The estimate spreads the messages in the bucket evenly across it. That is the rule of [Prometheus's percentile estimate from buckets](https://raw.githubusercontent.com/prometheus/prometheus/v2.53.0/promql/quantile.go), which assumes a linear distribution within a bucket. Other backends may interpolate differently, so the estimate moves when the edges move. Here the estimate is 20,019.8 ms and the nearest-rank value of the raw messages is 18,351.2 ms, so the estimate is 1,668.6 ms too high on this day.

Example `figure-bucket-hides-tail` (Python 3.13.16 · bm25s 0.3.16 · matplotlib 3.11.2 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Draw baseline day 1's message times twice, on one millisecond scale: each message as a point in the upper panel, and the
bucket counts for the same messages in the lower panel, each bucket drawn across the span it covers. The edges are the ones
bucket-edges-hide-tail uses. Every value the figure shows is printed first, and the nearest-rank p95 is drawn as a line."""
from lib import genai
from lib.dayrun import run_day
from lib.figures import ACCENT, INK, MUTED, new_figure, save
from lib.report import fmt_int, fmt_ms, fmt_share
from lib.stats import bucket_counts, nearest_rank

EDGES_S = genai.BUCKETS["gen_ai.client.invoke_agent.duration"]  # the conventions' advised upper bounds, in seconds, as there
runs = run_day("2026-12-08")
times = sorted(run.replied_ns - run.arrived_ns for run in runs)
n = len(times)
edges = [round(edge * 1_000_000_000) for edge in EDGES_S]      # integer nanoseconds, as every time here is
counts = bucket_counts(times, edges)
exact = nearest_rank(times, 95)
lows = [0] + edges                                             # each bucket starts at the edge before it
print("messages (n):", fmt_int(n))
for number, count in enumerate(counts):
    if number < len(edges):
        print(f"bucket above {fmt_ms(lows[number])} up to {fmt_ms(edges[number])}: {fmt_int(count)} messages, {fmt_share(count, n)}")
    else:
        print(f"bucket above {fmt_ms(lows[number])}: {fmt_int(count)} messages, {fmt_share(count, n)}")
print("p95, nearest rank of the raw values:", fmt_ms(exact))

fig, (top, bottom) = new_figure(rows=2, height=4.6, sharex=True)
top.scatter([t / 1e6 for t in times], [(i + 1) / n for i in range(n)], s=10, color=INK, label="each message")
for edge in edges:
    top.axvline(edge / 1e6, color=MUTED, linestyle=":", linewidth=0.8)
top.axvline(exact / 1e6, color=ACCENT, linestyle="--", linewidth=1.2, label="p95, nearest rank")
top.set_ylabel("share at or below")
top.legend(loc="lower right")
highs = edges + [edges[-1] + 10_000_000_000]                   # the last bucket is open; drawn 10 s wide, past the axis
centres = [(lo + hi) / 2 / 1e6 for lo, hi in zip(lows, highs)]
widths = [(hi - lo) / 1e6 for lo, hi in zip(lows, highs)]
bars = bottom.bar(centres, counts, width=widths, color=MUTED)
bottom.bar_label(bars, labels=[fmt_int(c) if c else "" for c in counts], padding=2)   # empty buckets carry no label
bottom.set_xticks([e / 1e6 for e in edges], [f"{e / 1e6:,.0f}" if e >= 10_240_000_000 else "" for e in edges])   # the small edges crowd the left
bottom.set_ylabel("messages")
bottom.set_xlim(0, 42000)                                      # set after the ticks, which would widen it
bottom.set_ylim(0, max(counts) * 1.15)
bottom.set_xlabel("message time, milliseconds; bucket edges as ticks")
save(fig, "bucket-hides-tail")
```

Output:

```text
messages (n): 200
bucket above 0.0 ms up to 10.0 ms: 0 messages, 0.0%
bucket above 10.0 ms up to 20.0 ms: 0 messages, 0.0%
bucket above 20.0 ms up to 40.0 ms: 0 messages, 0.0%
bucket above 40.0 ms up to 80.0 ms: 0 messages, 0.0%
bucket above 80.0 ms up to 160.0 ms: 0 messages, 0.0%
bucket above 160.0 ms up to 320.0 ms: 0 messages, 0.0%
bucket above 320.0 ms up to 640.0 ms: 0 messages, 0.0%
bucket above 640.0 ms up to 1,280.0 ms: 21 messages, 10.5%
bucket above 1,280.0 ms up to 2,560.0 ms: 65 messages, 32.5%
bucket above 2,560.0 ms up to 5,120.0 ms: 3 messages, 1.5%
bucket above 5,120.0 ms up to 10,240.0 ms: 16 messages, 8.0%
bucket above 10,240.0 ms up to 20,480.0 ms: 89 messages, 44.5%
bucket above 20,480.0 ms up to 40,960.0 ms: 6 messages, 3.0%
bucket above 40,960.0 ms up to 81,920.0 ms: 0 messages, 0.0%
bucket above 81,920.0 ms: 0 messages, 0.0%
p95, nearest rank of the raw values: 18,351.2 ms
figure: figures/bucket-hides-tail.svg
```

*Figure 7.2. Baseline day 1's messages as points, and as bucket counts, with the 95th percentile as a dashed line.*

![The 95th percentile falls in a bucket, and the bucket counts alone cannot say where in it the messages lie](https://rollingedition.ai/books/observability-for-llm-applications/2026.11.2/figures/bucket-hides-tail.svg)

Figure 7.2 draws the same messages twice on one millisecond scale. The upper panel plots each message at the share of messages at or below it, so the points climb. The dotted lines are the bucket edges, and the dashed line is the nearest-rank 95th percentile. The lower panel shows each bucket's count, drawn across the range the bucket covers. The 95th-percentile line falls inside a wide bucket, and nothing in the lower panel says where in that bucket the messages sit. That is what a bucket loses, and it is why the estimate is off.

**Working rule:** Set bucket edges from the question you will ask, and put an edge near each threshold you alert on. When a percentile falls inside a wide bucket, report the bucket and its count rather than an estimate to the millisecond, and keep the raw values whenever you can. An estimate from buckets is one rule applied to one set of edges, and it moves when the edges move.

## Queueing on recorded service times {#queueing-on-recorded-service-times}

A message's time is not only its own work. When a message arrives while the model is busy with another, it waits, and the wait is part of the time the user sees. A queue shows how that wait grows with load. Each arrival joins a line, the server takes one message at a time, and the load is the share of the server's time that arrivals ask for.

The numbers in this section are computed, not recorded. The code models one server. Its arrivals come at random, at a fixed average rate set by the load, which is a Poisson process: the gaps between arrivals are independent, with an exponential spread. Each message's service time is one of the day's recorded message times, drawn with replacement. Little's law says that the average number in a system equals its arrival rate times the average time each item spends in it, L = λW. [Little's 1961 proof](https://doi.org/10.1287/opre.9.3.383) establishes it, and [MIT's course notes on the M/M/1 queue](https://ocw.mit.edu/courses/2-854-introduction-to-manufacturing-systems-fall-2016/927056a1af54772a587fd84ad4951e71_MIT2_854F16_Mm1Queue.pdf) state it in the form used here.

Example `queue-on-service-times` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Queue baseline day 1's recorded message times behind one first-come, first-served server at three loads, with seeded Poisson
arrivals and each message's service drawn from the recorded times. The number in system is walked from the queue's events and
checked against the arrival rate times the time in system, and the last check compares exponential service with the M/M/1 formula."""
from lib.dayrun import run_day
from lib.report import fmt_int, fmt_ms
from lib.stats import nearest_rank

from fractions import Fraction

import numpy as np

SEED, N, CHECK_N = 20261208, 50_000, 200_000                   # one seed; messages per run; the M/M/1 check's run
recorded = [run.replied_ns - run.arrived_ns for run in run_day("2026-12-08")]   # the day's 200 recorded message times
mean_service = sum(recorded) / len(recorded)


recorded_services = lambda rng, n: rng.choice(np.asarray(recorded, dtype=np.int64), n)   # resampled with replacement
exponential_services = lambda rng, n: rng.exponential(mean_service, n).round().astype(np.int64)


def simulate(rng, rho, n, services):
    """Serve n messages arriving at rate rho / mean_service. Returns arrivals, waits, times in system, the last finish
    and the total service time, in ns."""
    arrivals = np.cumsum(rng.exponential(mean_service / rho, n)).round().astype(np.int64).tolist()
    finish, waits, sojourn, busy = 0, [], [], 0
    for arrive, serve in zip(arrivals, services(rng, n).tolist()):
        start = max(arrive, finish)          # the server finishes the message before it, then starts this one
        finish = start + serve
        waits.append(start - arrive)
        sojourn.append(finish - arrive)
        busy += serve
    return arrivals, waits, sojourn, finish, busy


print("mean recorded message time:", fmt_ms(round(mean_service)))
for rho in (0.5, 0.8, 0.9):
    arrivals, waits, sojourn, finish, busy = simulate(np.random.Generator(np.random.PCG64(SEED)), rho, N, recorded_services)
    span = finish - arrivals[0]                                # first arrival to last departure
    # Each arrival adds one to the count in system and each departure takes one away; the area under the count is L times the span.
    area, count, when = 0, 0, arrivals[0]
    for moment, step in sorted([(a, 1) for a in arrivals] + [(a + s, -1) for a, s in zip(arrivals, sojourn)]):
        area, count, when = area + count * (moment - when), count + step, moment
    number, rate_times_time = Fraction(area, span), Fraction(N, span) * Fraction(sum(sojourn), N)   # L, and lambda W
    print(f"load {rho}, utilisation, computed: {busy / span:.2f}")
    print(f"load {rho}, wait before service, computed, p95 (n = {fmt_int(N)}):", fmt_ms(nearest_rank(waits, 95)))
    print(f"load {rho}, number in system, time average, computed: {float(number):.2f}")
    print(f"load {rho}, arrival rate times time in system, computed: {float(rate_times_time):.2f}")
    assert number == rate_times_time     # exact, with no tolerance: the window starts at the first arrival and ends at the last departure

# M/M/1: the mean time in system is 1 / (mu - lambda), which is mean_service / (1 - rho) for exponential service.
sojourn = simulate(np.random.Generator(np.random.PCG64(SEED)), 0.8, CHECK_N, exponential_services)[2]
simulated, formula = sum(sojourn) / CHECK_N, mean_service / (1 - 0.8)
print(f"exponential service, load 0.8, mean time in system, simulated (n = {fmt_int(CHECK_N)}):", fmt_ms(round(simulated)))
print("exponential service, load 0.8, mean time in system, formula:", fmt_ms(round(formula)))
assert abs(simulated - formula) / formula < 0.02
```

Output:

```text
mean recorded message time: 8,019.0 ms
load 0.5, utilisation, computed: 0.50
load 0.5, wait before service, computed, p95 (n = 50,000): 27,983.0 ms
load 0.5, number in system, time average, computed: 0.91
load 0.5, arrival rate times time in system, computed: 0.91
load 0.8, utilisation, computed: 0.80
load 0.8, wait before service, computed, p95 (n = 50,000): 82,817.5 ms
load 0.8, number in system, time average, computed: 3.31
load 0.8, arrival rate times time in system, computed: 3.31
load 0.9, utilisation, computed: 0.90
load 0.9, wait before service, computed, p95 (n = 50,000): 179,463.5 ms
load 0.9, number in system, time average, computed: 7.26
load 0.9, arrival rate times time in system, computed: 7.26
exponential service, load 0.8, mean time in system, simulated (n = 200,000): 40,422.0 ms
exponential service, load 0.8, mean time in system, formula: 40,094.8 ms
```

The output covers loads of 0.5, 0.8 and 0.9, each with the same seed, and then one more check where a formula exists. The mean recorded message time is 8,019.0 ms, the service each message takes on average, and at a load of 0.5 the server's utilisation is 0.50.

The 95th-percentile wait before service is 27,983.0 ms at load 0.5, 82,817.5 ms at 0.8, and 179,463.5 ms at 0.9. The waits climb more steeply than the load.

The number in system follows the same curve. At load 0.8 it averages 3.31, and the arrival rate times the time in system gives 3.31. The code finds the first from the queue's events over time and the second from the arrival rate and the mean time in system, and asserts that they are equal at every load. On a sample path whose window runs from the first arrival to the last departure, Little's law holds exactly, so the assert allows no tolerance.

The M/M/1 formula, the mean time in system for one server with exponential service, is exact only for exponential service times, and the recorded times are not exponential. So the code checks the simulation on its own terms first. With exponential service at load 0.8 over 200,000 messages, the simulated mean time in system is 40,422.0 ms, and the formula gives 40,094.8 ms. The code asserts that the two agree within 2%. M/G/1, a single server with any service distribution, has a mean formula of its own, and this chapter leaves that check out.

This is a model of one server, not of Ambrewick's deployment. Each message's whole recorded time is one service, which is how the queue treats a message, and its arrivals ignore the day's real arrival times. The waits are therefore what one server with this mix of messages would give, and they are not what the day did.

**Working rule:** Read a queue at the load you expect and at a higher one before you accept a tail or add capacity. Use recorded service times when you have them, label every number the simulation computes, and check the simulation against a formula only where the formula's assumptions hold.

## What goes wrong in production {#latency-sources-in-production}

Three things change when these numbers leave the replay. First, production spans leave gaps. The recorder's gaps between calls total 651.4 ms over the day. They are real time in the message, but they belong to no span, so a critical path built from spans can cover less than the message's full time. Read the path's share beside the message time, and treat a low share as a question for the trace, not as an answer.

Second, the histogram a service exports has the edges its configuration sets, which may not be the conventions' advised ones. A percentile read from buckets takes on the [error](#how-a-span-records-failure) of its edges, as the bucket estimate shows on this day's messages. Chapter 9 sets its objectives on these latencies, so the edges belong in that decision as well.

Third, a route with few messages a day gets a 95th percentile with a wide [interval](#tail-percentiles-with-intervals), and a dashboard that shows only the point looks exact. Put the count and the interval on the same panel, or leave the percentile off it.

**Working rule:** Before you publish a latency number from production, print its count and its interval beside it, and say which kind of time it is: a span's time, a bucket's estimate, or a replay's sum. When the path's share or the bucket's edges are unknown, state that with the number instead of letting the number stand alone.

## The decisions this chapter made {#latency-sources-decisions}

Each of these is a judgement we could get wrong. Each gives its reason and the example that tests it.

- We read the critical path from the spans, and we show the overlap case on a constructed tree, because no recorded message has overlapping calls. `critical-path-one-message` checks that the path covers the whole replayed message, and that the constructed tree's span b is off the path.
- We report time to first chunk beside the same call's total time, and we split it with the counters, so that a first chunk is never read alone. `time-to-first-chunk-by-route` and `prefill-generation-split` print both on the same calls.
- We print nearest-rank percentiles with their counts, and an interval on each 95th percentile from seeded bootstrap resamples of messages. `percentiles-by-route` names the routes under 20 messages, whose 95th percentile is their largest message, and checks the one overlap the prose relies on.
- We use the edges the GenAI conventions advise for message time, and we say so, because a service's own edges may differ. `bucket-edges-hide-tail` prints the estimate's error on this day, and `figure-bucket-hides-tail` draws the raw values beside the counts.
- We simulate queues only on recorded service times, and we label every queue number computed. `queue-on-service-times` finds the number in system from the queue's events and checks it against the arrival rate times the time in system at each load, and it checks the M/M/1 formula only with exponential service.
- We rank routes' tails only where their intervals do not overlap, because one day of messages cannot order them. On this day that leaves most of the answering routes unordered, so the firm difference is whether a route answers at all, not which answering route has the worst tail.

# Find the step that failed

By the end of this chapter you can find which step of a message failed, how often, and why, and print each count with the rows it came from. The case puts the question plainly. A user who got no useful answer cannot tell from the log why. The router may have sent the request to the wrong route, or to the fallback reply. The model may have written a tool call the parser cannot read, or a reply cut off at its token cap. The contacts server may have returned an error, or no answer at all. Which of these happened, and how often?

Baseline day 1 answers the how-often question from its real replies. Of its 200 messages, 41 went to the wrong route, and not one span ended in error. Those are the day's real failures. The incident day needs a second kind of count, because we injected its faults: a window in which the contacts server answers too late, one in which the model refuses every request, and one in which the contacts server returns error results. Each injected fault is labelled, and its counts sit in their own rows, never folded into baseline day 1's rates. Every table that prints an injected count repeats the label, and nothing on the incident day is a real outage.

The replays run on the virtual clock of [Replay and the virtual clock](#replay-and-the-virtual-clock). The case's traffic was generated for this book, so the rates here are the book's own and describe no service.

The chapter builds one query per failure mode, from the status a span records to the wrong route.

## How a span records failure {#how-a-span-records-failure}

A span records its outcome in its status. The conventions ask instrumentation to set the status to `Error` when an operation ends with an error, and to leave it unset when nothing went wrong ([recording errors](https://raw.githubusercontent.com/open-telemetry/semantic-conventions/v1.45.0/docs/general/recording-errors.md), v1.45.0). The same page asks for `error.type` on a failed operation.

A span's status is unset, ok or error. `error.type` names the error: the class name the package writes, or a registry value where one exists, so failures can be counted by kind. We invent no registry value.

We use one more word for the same thing. An error is a span whose status is ERROR. A message has an error when any of its spans is ERROR. That is the error chapter 10's [the CI gate](#the-ci-gate) counts. Two other bad outcomes are not errors. A reply cut at its token cap is a quality finding, and so is a route reply that names no route. Both are counted below, and neither sets a span's status.

The registry offers few values to choose from. Its fallback is `_OTHER`, and it has no value for a timeout or for an HTTP 429, which are the two failures this chapter meets most. The registry asks for values that are predictable and [low in cardinality](#cardinality), and it lists `timeout` and `500` as examples, not as defined values ([error.md](https://raw.githubusercontent.com/open-telemetry/semantic-conventions/v1.45.0/docs/registry/attributes/error.md), v1.45.0). So we write the class name the package raises: `MCPError` for a read timeout, `RateLimitError` for a refused model request, and `ModelUnavailable` for the assistant's own give-up. We write the short class name, where the registry's examples are fully qualified. Other instrumentation writes the qualified one, such as the openai instrumentation's `openai.RateLimitError`, and the assistant's own `exception.type` on the same span is qualified. The injected 429 raises the book's `RateLimitError`, which stands in for the client's exception of that name. The value is therefore the book's, and a deployment that uses the client's own exception will read a different class name in the same place.

An exception is recorded apart from the status. When the OpenTelemetry Python SDK, 1.45.2 in this book, records an exception, it adds an `exception` event to the span and leaves the status unset. The two helpers that wrap a span, `start_as_current_span` and `use_span`, are the exception to that: when an exception escapes them, they also set the status to ERROR by default. The recording-errors page asks for a different place: it says an exception that fails an operation should be recorded as a log record. We recommend keeping the SDK's event while the receiver holds spans. Every query in this chapter reads spans, and the counts depend on the status. A deployment with a log pipeline can take the other route, as long as the status and `error.type` still reach the spans.

Example `error-status-by-step` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Which spans end with ERROR, and what error.type each carries, on the incident day (injected, labelled) and on baseline
day 1 (real). The point rests on the baseline's zero ERROR spans: a wrong route is not a span error, so the status cannot
find it, and the incident's faults look alike from outside."""
from collections import Counter

from lib.dayrun import run_day_traced
from lib.report import fmt_int

real = run_day_traced("2026-12-08", live=False)  # baseline day 1, replayed: no fault is injected into it
real_errors = [row for row in real.spans if row["status"] == "ERROR"]
print("real ERROR spans, baseline day 1 (4B):", fmt_int(len(real_errors)))
assert not real_errors  # the baseline's failures are wrong routes and fallback replies, which set no span status

live = run_day_traced("2026-12-09")  # live: the contacts server runs the injected faults over stdio
rows = live.spans + live.server
errors = [row for row in rows if row["status"] == "ERROR"]
print("ERROR spans, incident day (injected):", fmt_int(len(errors)))
# Each injected fault labels every span it touches, so the label itself tells an injected error from a real one.
assert all(row["attributes"].get("ambrewick.incident.injected") for row in errors)  # every ERROR span is injected
counts = Counter((row["name"], row["attributes"].get("error.type", "none")) for row in errors)
for (name, error_type), count in sorted(counts.items()):
    print(f"{name}, error.type {error_type}, injected: {count}")
```

Output:

```text
real ERROR spans, baseline day 1 (4B): 0
ERROR spans, incident day (injected): 75
MCP send tools/call find_contact, error.type none, injected: 4
chat qwen3-4b-instruct-2507, error.type RateLimitError, injected: 47
contacts.lookup, error.type none, injected: 3
execute_tool find_contact, error.type MCPError, injected: 4
execute_tool find_contact, error.type tool_error, injected: 3
invoke_agent ambrewick-assistant, error.type ModelUnavailable, injected: 11
tools/call find_contact, error.type tool_error, injected: 3
```

Baseline day 1, replayed, has no ERROR span at all, and that zero is the point: a wrong route sets no status. So the day's real failures are not in this table at all, and the rest of the chapter counts them another way. The incident day runs live, so that the contacts server applies its faults. It has 75 ERROR spans, and the example asserts that every one of them carries the injected label.

Read the rows by status first, and by `error.type` second. Some ERROR spans carry no `error.type` at all. The MCP SDK's client span, `MCP send tools/call find_contact`, for a timed-out call is one kind: there are 4 of those. The contacts server's `contacts.lookup` span for an injected crash is the other: 3 of those. The default described above sets ERROR when the crash escapes the span, and nothing sets `error.type`. A count by `error.type` alone would miss both. The other rows are the kinds the later sections explain. Refused model requests carry `RateLimitError`, 47 of them. Messages that got no reply end with a root span that reads `ModelUnavailable`, 11. The contacts calls that failed appear under three names: `execute_tool find_contact` on the assistant's attempt, `MCP send tools/call find_contact` on the client span, and `tools/call find_contact` on the server's span. The sections on timeouts and error results read each one.

**Working rule:** Count failures by span status, and print each `error.type` beside its count. A span with no `error.type` is still an error, so never filter on the attribute to find failures. Keep real and injected counts in separate rows, and label each injected row where it appears.

## Replies cut at the cap {#replies-cut-at-the-cap}

The status rule in [the first section](#how-a-span-records-failure) catches a failure that raises, and a reply cut at its token cap raises nothing. Some replies stop because the model reached that cap, not because it finished. The assistant records the runtime's finish reason in `gen_ai.response.finish_reasons`, an array with one entry per generation, in the order of the generation's choices. The finish reason says why the model stopped: on its own (`stop`) or at the token cap (`length`). The GenAI conventions, at 0.1.0, define the inference span's values in the same terms: an interrupted generation reports the provider's reason or `interrupted`, and `error` is reported when a reason was expected and not received ([client inference span](https://raw.githubusercontent.com/open-telemetry/semantic-conventions-genai/v0.1.0/docs/gen-ai/client-inference.md), note 18). So a `length` reply is not an error, and we do not count it as one. [The agent harnesses' finish reason](https://rollingedition.com/concepts/large-language-models/finish-reason) is the same idea.

Two facts about this runtime shape the check. First, it never reports `tool_calls`. A model's tool call comes back as text inside the reply, and the finish reason stays `stop`, so the finish reason cannot show a tool call. The next section deals with that case. Second, the answer step has a cap of 160 tokens. The cap is the same in every release and recording. It was set once, before any recording this book reads, and no recording was edited to produce a cut.

Example `truncated-replies` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Which model replies the runtime cut at its token cap, read from the finish reason the runtime recorded for each
request: baseline day 1 (the 4B, release r0) and the model swap (the 0.6B, release r2). A cut reply has finish reason
length. The runtime never reports tool_calls, so a reply with a tool call is not found this way (malformed-tool-calls)."""
import json
from collections import Counter

from lib.dayrun import DATA, run_day_traced
from lib.report import fmt_int


def finish_reasons(recording):
    """The finish reason of every model request in one recording, counted by step and reason."""
    rows = [json.loads(line) for line in (DATA / recording / "traces.jsonl").read_text(encoding="utf-8").splitlines()]
    return [row for row in rows if row["kind"] == "model"], Counter(
        (row["step"], row["finish_reason"]) for row in rows if row["kind"] == "model")

base_rows, base = finish_reasons("baseline-day-1")
for step in ("route", "answer"):
    print(f"baseline day 1, {step} requests, finish reason stop: {fmt_int(base[(step, 'stop')])}")
    print(f"baseline day 1, {step} requests, finish reason length: {fmt_int(base[(step, 'length')])}")
# The replay answers from the same recording, and its chat spans carry the finish reason in an array.
replayed = run_day_traced("2026-12-08", live=False).spans
chat = [row for row in replayed if row["name"].startswith("chat")]
reasons = Counter(reason for row in chat for reason in row["attributes"]["gen_ai.response.finish_reasons"])
print(f"baseline day 1, chat spans replayed with finish reason stop: {fmt_int(reasons['stop'])}")
assert reasons["length"] == 0 and reasons["stop"] == len(base_rows)  # the replay's spans match the recording

swap_rows, swap = finish_reasons("release-model-swap")
manifest = json.loads((DATA / "release-model-swap" / "manifest.json").read_text(encoding="utf-8"))
for step in ("route", "answer"):
    print(f"model swap (0.6B, release r2), {step} requests, finish reason length: {fmt_int(swap[(step, 'length')])}")
cut = [row for row in swap_rows if row["finish_reason"] == "length"]
print(f"model swap, answer cap in tokens: {manifest['answer_max_tokens']}")
print(f"model swap, cut answer, completion tokens: {cut[0]['completion_tokens']}")
assert len(cut) == 1 and cut[0]["step"] == "answer"  # one cut reply, and it is an answer
assert cut[0]["completion_tokens"] == manifest["answer_max_tokens"]  # cut at the cap, not at a stop token
```

Output:

```text
baseline day 1, route requests, finish reason stop: 200
baseline day 1, route requests, finish reason length: 0
baseline day 1, answer requests, finish reason stop: 121
baseline day 1, answer requests, finish reason length: 0
baseline day 1, chat spans replayed with finish reason stop: 321
model swap (0.6B, release r2), route requests, finish reason length: 0
model swap (0.6B, release r2), answer requests, finish reason length: 1
model swap, answer cap in tokens: 160
model swap, cut answer, completion tokens: 160
```

No reply from the 4B reached the cap. Its 200 route replies and 121 answers all stopped on their own, and the replay's chat spans carry the same reasons: 321 of them, all `stop`.

The model-swap release runs Qwen3-0.6B, and it adds `/no_think` to its prompt, so its differences from baseline day 1 come from the smaller model and the suffix together. Here the cut shows up. None of its route replies was cut, and its answer step cut 1 reply, at 160 tokens, which is the cap.

That cut reply is a quality finding. The span is not an error, and the user receives a reply that stopped short. We file it under quality and read the text before deciding what it means.

**Working rule:** Count the `length` finish reasons for each step on every release, before you call its replies complete, and print the cap beside the count. A zero on one recording says nothing about another. Read a cut reply as a quality finding, and never file it as an error.

## Tool calls that do not parse {#tool-calls-that-do-not-parse}

When the model wants a tool, it writes a `<tool_call>` block into its reply, and the assistant reads the block back. The runtime's finish reason cannot show a bad block, because a reply with a broken block still stops on its own. A malformed call is found only by parsing the reply. A block with no closing tag is malformed. So is a body that is not JSON, a call with no name, or one whose arguments are not an object. Each malformed call is counted once on its message, and the assistant tells the model that the call could not be read and asks it to answer without a tool.

A different failure reaches the tool itself. A call can parse and still fail the argument model of its tool. That is not a malformed reply. The tool attempt ends ERROR, with `error.type` set to the class `ValidationError`, and [the query section](#querying-each-failure-mode) counts those among the tool attempts.

Example `malformed-tool-calls` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Which answer replies carry a tool call the parser cannot read, on baseline day 1 (the 4B) and the model swap (the 0.6B).
A malformed call is found by parsing the reply, because its finish reason is stop either way. The constructed replies
at the end are not recorded and never become spans: they show that the parser rejects what it should."""
import glob
import json
from pathlib import Path

from lib.assistant import MalformedToolCall, parse_tool_call
from lib.dayrun import DATA, run_day_traced
from lib.report import fmt_int


def check_answers(recording):
    """Parse every answer reply in one recording. Returns the reply count, the replies with a tool call, and the
    message IDs whose reply the parser rejects."""
    paths = sorted(glob.glob(str(DATA / recording / "calls" / "*.json")))
    calls = [json.loads(Path(path).read_text(encoding="utf-8")) for path in paths]
    answers = sorted((call for call in calls if call["kind"] == "model" and call["step"] == "answer"),
                     key=lambda call: call["seq"])  # the recorder's sequence number, unique per request
    tool_calls, rejected = 0, []
    for call in answers:
        try:
            tool_calls += parse_tool_call(call["text"]) is not None
        except MalformedToolCall:
            rejected.append(call["message_id"])
    return len(answers), tool_calls, rejected


answers, tool_calls, rejected = check_answers("baseline-day-1")
print(f"baseline day 1 (4B), answer replies: {fmt_int(answers)}")
print(f"baseline day 1 (4B), replies with a tool call: {fmt_int(tool_calls)}")
print(f"baseline day 1 (4B), malformed tool calls: {fmt_int(len(rejected))}")
# The replay parses the same recorded texts with the same parser, so its count should agree with the parse above.
replayed = sum(run.outcome.malformed_tool_calls for run in run_day_traced("2026-12-08", live=False).runs)
print(f"baseline day 1 (4B), malformed tool calls in the replay: {fmt_int(replayed)}")
assert not rejected and replayed == 0

answers, tool_calls, rejected = check_answers("release-model-swap")
print(f"model swap (0.6B, release r2), answer replies: {fmt_int(answers)}")
print(f"model swap (0.6B, release r2), replies with a tool call: {fmt_int(tool_calls)}")  # one call tests nothing
print(f"model swap (0.6B, release r2), malformed tool calls: {fmt_int(len(rejected))}")
assert not rejected

# Constructed, not recorded: two replies a model could write, passed straight to the parser.
for label, text in {"unclosed block": '<tool_call>{"name": "find_contact", "arguments": {}',
                    "body is not JSON": "<tool_call>find the contact</tool_call>"}.items():
    try:
        parse_tool_call(text)
        raise AssertionError(f"{label} was not rejected")
    except MalformedToolCall:
        print(f"constructed reply, {label}, rejected by the parser: yes")
```

Output:

```text
baseline day 1 (4B), answer replies: 121
baseline day 1 (4B), replies with a tool call: 10
baseline day 1 (4B), malformed tool calls: 0
baseline day 1 (4B), malformed tool calls in the replay: 0
model swap (0.6B, release r2), answer replies: 57
model swap (0.6B, release r2), replies with a tool call: 1
model swap (0.6B, release r2), malformed tool calls: 0
constructed reply, unclosed block, rejected by the parser: yes
constructed reply, body is not JSON, rejected by the parser: yes
```

No recorded reply on baseline day 1 held a broken block. The 4B wrote 121 answer replies, 10 of which carried a tool call, and the parser rejected 0 of them. The replay's outcome, which counts parse failures and schema rejections together, finds 0, which agrees.

The model-swap release, Qwen3-0.6B with `/no_think` on its prompt, wrote 57 answers, and only 1 of them carried a tool call. That call parsed. One call tests nothing about a small model's tool use, so this section makes no claim about it.

Neither recording holds a broken block. To show what the parser refuses, we pass two replies written for this chapter straight to it, and it rejects both. The replies were never recorded and never become spans, rows or recordings, so they say nothing about the recorded day.

The receiver cannot find a parse failure, though. A malformed reply raises inside the assistant and is counted on the message's outcome, and no span records it as an error. The count above therefore comes from the replies. [The query section](#querying-each-failure-mode) says what the receiver can and cannot show.

**Working rule:** Parse every reply that could carry a tool call, and count malformed replies with the parser's own count, never with a finish reason. Print the replies that carry a call beside that count, so a reader can see how small a sample of tool use it is.

## Retries under a timeout {#retries-under-a-timeout}

The status rule in [the first section](#how-a-span-records-failure) catches a failure that raises, and the first injected fault is one: a timeout raises across the process boundary. The contacts server is a separate process, and `find_contact` runs there, so its failures reach the assistant as the MCP SDK raises them. We injected this fault into the incident day. Between 13:00 and 13:12 UTC, the contacts server answers `find_contact` only after the client's read timeout of 2,000.0 ms, and the client gives up. The tool wrapper waits and tries once more. [Chapter 4](#errors-across-the-boundary) explains how the SDK raises that timeout as an exception and not as a reply.

A retry is another attempt at a failed call, recorded as its own span. We recommend one span per attempt, and we record each attempt of a tool call as its own `execute_tool` span, with an `ambrewick.attempt` number. A failed attempt is therefore an ERROR span, and the call's success appears on the attempt that succeeded. No span describes the whole call. [Chapter 4's choice](#errors-across-the-boundary) gives the reason, and the first attempt's timeout is one of the failures the user's message met, so it counts.

Example `retries-under-incident` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""What each injected window does to the calls it covers, on the incident day, run live so the contacts server applies its
faults. A timed-out find_contact is two attempts that end ERROR with MCP code -32001, the retry starting after the read
timeout and the retry delay; a refused model request is retried on the assistant's backoff. Every line here is labelled
with its window: injected, not a natural rate."""
import tomllib

from lib import inject
from lib.case import CASE_DIR
from lib.dayrun import run_day_traced
from lib.report import fmt_int, fmt_ms
from lib.tools import REQUEST_TIMEOUT_NS, RETRY_DELAY_NS

live = run_day_traced("2026-12-09")
# Spans carry no message ID, so each message is found by its trace: the root spans come in arrival order, as the runs do.
roots = sorted((row for row in live.spans if row["name"].startswith("invoke_agent")), key=lambda row: row["trace_seq"])
message_of = {root["trace_id"]: run.message.message_id for root, run in zip(roots, live.runs, strict=True)}
windows = {incident.incident_id: incident for incident in inject.load_incidents()}
schedule = {row["id"]: row for row in tomllib.loads((CASE_DIR / "incidents.toml").read_text(encoding="utf-8"))["incident"]}
finds = [row for row in live.spans if row["name"] == "execute_tool find_contact"]
refused = [row for row in live.spans if row["attributes"].get("error.type") == "RateLimitError"]


def inside(name, row):
    """Whether a span starts inside the named window (the window's virtual start, inclusive, to its end)."""
    return windows[name].start_ns <= row["start_ns"] < windows[name].end_ns


def say(name, label, value):
    """Print one labelled value for a window."""
    print(f"{name} (injected), {label}: {value}")


TIMEOUT = "inc-contacts-timeout"
# The schedule's stamps read 2026-12-09T13:00:00.000000Z, so characters 11 to 16 hold the UTC clock time.
say(TIMEOUT, "window start (UTC)", schedule[TIMEOUT]["start"][11:16])
say(TIMEOUT, "window end (UTC)", schedule[TIMEOUT]["end"][11:16])
timeouts = sorted((row for row in finds if inside(TIMEOUT, row)
                   and row["attributes"].get("error.type") == "MCPError"), key=lambda row: row["start_ns"])
assert all(row["status"] == "ERROR" and row["attributes"]["ambrewick.mcp.error_code"] == -32001 for row in timeouts)
assert all(row["end_ns"] - row["start_ns"] == REQUEST_TIMEOUT_NS for row in timeouts)  # each attempt waits the read timeout
say(TIMEOUT, "attempts that time out", fmt_int(len(timeouts)))
say(TIMEOUT, "MCP error code", timeouts[0]["attributes"]["ambrewick.mcp.error_code"])
say(TIMEOUT, "read timeout", fmt_ms(REQUEST_TIMEOUT_NS))
pairs = [(a, b) for a, b in zip(timeouts, timeouts[1:]) if a["trace_id"] == b["trace_id"]]
assert all(b["start_ns"] - a["start_ns"] == REQUEST_TIMEOUT_NS + RETRY_DELAY_NS for a, b in pairs)
say(TIMEOUT, "retries", fmt_int(len(pairs)))
say(TIMEOUT, "retry wait", fmt_ms(RETRY_DELAY_NS))
say(TIMEOUT, "retry starts after the first attempt", fmt_ms(pairs[0][1]["start_ns"] - pairs[0][0]["start_ns"]))

errors = [row for row in finds if inside("inc-mcp-error", row)]
say("inc-mcp-error", "retries", fmt_int(sum(row["attributes"]["ambrewick.attempt"] > 1 for row in errors)))

replied = [run for run in live.runs if run.outcome.source == "model" and run.message.message_id in schedule["inc-rate-limit"]["message_ids"]]
retried = [run for run in replied if any(message_of[row["trace_id"]] == run.message.message_id for row in refused)]
say("inc-rate-limit", "messages that got a reply after a refused attempt", fmt_int(len(retried)))
assert len(retried) == len(replied)  # every reply in the window came after a refusal
```

Output:

```text
inc-contacts-timeout (injected), window start (UTC): 13:00
inc-contacts-timeout (injected), window end (UTC): 13:12
inc-contacts-timeout (injected), attempts that time out: 4
inc-contacts-timeout (injected), MCP error code: -32001
inc-contacts-timeout (injected), read timeout: 2,000.0 ms
inc-contacts-timeout (injected), retries: 2
inc-contacts-timeout (injected), retry wait: 500.0 ms
inc-contacts-timeout (injected), retry starts after the first attempt: 2,500.0 ms
inc-mcp-error (injected), retries: 0
inc-rate-limit (injected), messages that got a reply after a refused attempt: 1
```

Here the incident day runs live, so the contacts server applies the fault, and each span is grouped by its window. Every line names its window and says injected. In the timeout window, the timed-out attempts were 4. Each ends ERROR, with `error.type` `MCPError` and the MCP code on `ambrewick.mcp.error_code`. The code is -32001, the SDK's name for a read timeout and not a protocol code, as [chapter 4](#errors-across-the-boundary) says. The retries were 2. Both timed-out messages' retries timed out too, so the tool returned its timed-out reply to the model. Each second attempt starts 2,500.0 ms after its first, which is the read timeout plus the wait before the retry.

The model's window works the same way, but its failures are refusals. Every model request in the window is answered with a 429, and the assistant retries with a backoff. Each refused attempt is a zero-length chat span, ERROR, with `error.type` `RateLimitError`, and the injected window refused 47 requests. Once the backoff runs out, the message ends with no reply: 11 messages did. One message got a reply after a refused attempt, which is 1. By the span rule, that message counts as an error, although its user got the reply. The count follows the spans. [The production section](#find-the-failure-in-production) says what that does to a rate.

**Working rule:** Count a failed attempt as a failure even when the call later succeeds, and name its window before you count it as injected.

## MCP errors {#mcp-errors}

The contacts server has a second way to fail, and it raises nothing. The MCP tools specification says that a tool's own failure comes back as a result with `isError` set, and not as a protocol error ([tools](https://modelcontextprotocol.io/specification/2026-07-28/server/tools), revision 2026-07-28). The MCP Python SDK, 2.3.0 in this book, follows that rule. The injected `mcp-error` window makes every `find_contact` call in its window come back as an error result, and the client hands the result back to the assistant as a reply.

An error result is not an exception, so there is no exception to name. The attempt ends ERROR with `error.type` `tool_error`, the value that the MCP conventions define for an `isError` result ([MCP conventions](https://raw.githubusercontent.com/open-telemetry/semantic-conventions-genai/v0.1.0/docs/gen-ai/mcp.md), v0.1.0). Its status description reads "find_contact returned an error result". No exception event is written, and no retry follows.

The incident day's rows show the three records. The assistant recorded 3 attempts as `tool_error`, and the server recorded the same calls as `tool_error` too, 3 of them. The window's retries line reads 0, so none of these attempts was retried. The contacts server's `contacts.lookup` span is also ERROR for these calls, and it carries no `error.type`. The conventions ask for `tool_error` on the client span too, and for `error.type` on any failed client span, the exception's class name for a timeout. The MCP SDK at 2.3.0 departs from both: its client span for an error result stays unset, and its span for a timeout is ERROR with no `error.type`. The only client-side ERROR rows in [the first table](#how-a-span-records-failure) are the 4 timeouts.

One injected fault therefore leaves three ERROR records. A count of spans by status counts it three times. The failure a user's message met is the attempt, because that is the operation the message's own call made. The server's spans are the cause, and they join the message's trace through the context that [chapter 4](#traceparent-in-meta) propagates. The [query section](#querying-each-failure-mode) pairs each error-result attempt with the server span in its trace: 3 pairs.

**Working rule:** Count a failed operation once, on the span the caller made, and read the server's span beside it for the cause. With the MCP SDK at this version, expect the client's span to stay unset for an error result, though the conventions ask for `tool_error`; count by the caller's attempt either way.

## Wrong routes against the labels {#wrong-routes-against-labels}

A wrong route is the one failure with no error anywhere in the trace. The call succeeds, its reply stops on its own, and the answer is a fallback reply, or a tool route the message did not need. To find it, the book needs a source of truth, and the case has one. MASSIVE labels each utterance with a scenario. The scenario table maps each scenario to one route, and the routes are `calendar`, `alarms`, `lists`, `messages`, `devices`, `media` and `fallback`. A scenario goes to the route whose tool or articles resolve it, and to `fallback` only when no tool and no article do. A wrong route is a routed choice that differs from the table's. The router writes its choice on the route span, and the check event on that span holds the table's answer, so the trace records whether the route was right.

The fallback reply is defined in [chapter 1](#where-the-time-went-in-twenty-messages). The table adds the rule for when it is the right answer. It is right for a message that no tool or article resolves, and for no other message. A fallback reply to any other scenario is a wrong route that the user sees as a refusal. The check is code, and it reads the trace, not the reply's text. Judging whether an answer is right is a separate job, and [Evaluating LLM Applications](https://rollingedition.com/concepts/llm-evaluation/code-check) covers the checks that read a reply.

The dev day shows the case in small. Of its 20 messages, 5 were routed wrong, and 3 of those got the fallback reply for a scenario that needed a tool or an article.

Example `wrong-routes-by-label` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""How often the router chose a route other than the scenario table's, on baseline day 1 (the 4B), the same messages under
the 0.6B (the model swap, from its recorded route replies) and the dev day. Each message's check event on its route span
holds the table's answer; the 0.6B's replies are read with the same parser. The interval is a bootstrap over messages."""
import json
from fractions import Fraction

from lib.assistant import parse_route
from lib.case import load_messages, scenario_to_route
from lib.dayrun import DATA, run_day, run_day_traced
from lib.report import fmt_int, fmt_share
from lib.stats import bootstrap_interval


def recorded_routes(recording, day):
    """(expected, chosen) for each route reply in one recording, in order. A reply that names no route is the fallback."""
    messages = {message.message_id: message for message in load_messages(day)}
    paths = sorted((DATA / recording / "calls").glob("*.json"))
    calls = sorted((json.loads(path.read_text(encoding="utf-8")) for path in paths), key=lambda call: call["seq"])
    return [(scenario_to_route(messages[c["message_id"]].scenario), parse_route(c["text"]) or "fallback")
            for c in calls if c["kind"] == "model" and c["step"] == "route"]


traced = run_day_traced("2026-12-08", live=False)
runs = traced.runs
# The check event is on each route span: the trace itself says whether the route was correct.
checks = [event["attributes"] for row in traced.spans for event in row["events"] if event["name"] == "ambrewick.check"]
wrong = [run.outcome.route != run.outcome.expected_route for run in runs]
assert len(checks) == len(runs) and sum(not check["ambrewick.route.correct"] for check in checks) == sum(wrong)
print(f"baseline day 1 (4B), messages: {fmt_int(len(runs))}")
RESAMPLES = 2000
low, high = bootstrap_interval(wrong, lambda units: Fraction(sum(units), len(units)), n=RESAMPLES)
print(f"bootstrap resamples of messages, baseline day 1: {fmt_int(RESAMPLES)}")
print(f"wrong routes, baseline day 1, 95% interval: {fmt_share(low.numerator, low.denominator)} to {fmt_share(high.numerator, high.denominator)}")
for route in sorted({run.outcome.expected_route for run in runs}):
    print(f"{route}, wrong routes of {fmt_int(sum(run.outcome.expected_route == route for run in runs))} messages: "
          f"{fmt_int(sum(run.outcome.route != route for run in runs if run.outcome.expected_route == route))}")
print("fallback replies to a scenario that is not fallback, baseline day 1: "
      f"{fmt_int(sum(run.outcome.route == 'fallback' and run.outcome.expected_route != 'fallback' for run in runs))}")

# The same messages under the 0.6B, from its recorded replies; the 4B's recorded replies must give the replay's count.
base = recorded_routes("baseline-day-1", "2026-12-08")
assert sum(expected != chosen for expected, chosen in base) == sum(wrong)
swap = recorded_routes("release-model-swap", "2026-12-08")
print(f"wrong routes, model swap (0.6B, release r2): {fmt_int(sum(e != c for e, c in swap))} of {fmt_int(len(swap))} messages")
print("fallback replies to a scenario that is not fallback, model swap: "
      f"{fmt_int(sum(c == 'fallback' and e != 'fallback' for e, c in swap))}")

# The dev day's 20 messages, for chapter 1's fallback replies, checked against the same table.
dev = run_day("2026-12-07")
print(f"dev day, messages: {fmt_int(len(dev))}")
print(f"wrong routes, dev day (20 messages): {fmt_int(sum(run.outcome.route != run.outcome.expected_route for run in dev))}")
print(f"fallback replies to a scenario that is not fallback, dev day: {fmt_int(sum(run.outcome.route == 'fallback' and run.outcome.expected_route != 'fallback' for run in dev))}")
```

Output:

```text
baseline day 1 (4B), messages: 200
bootstrap resamples of messages, baseline day 1: 2,000
wrong routes, baseline day 1, 95% interval: 15.0% to 26.5%
alarms, wrong routes of 6 messages: 0
calendar, wrong routes of 42 messages: 16
devices, wrong routes of 17 messages: 1
fallback, wrong routes of 82 messages: 11
lists, wrong routes of 7 messages: 0
media, wrong routes of 29 messages: 3
messages, wrong routes of 17 messages: 10
fallback replies to a scenario that is not fallback, baseline day 1: 18
wrong routes, model swap (0.6B, release r2): 83 of 200 messages
fallback replies to a scenario that is not fallback, model swap: 68
dev day, messages: 20
wrong routes, dev day (20 messages): 5
fallback replies to a scenario that is not fallback, dev day: 3
```

On baseline day 1 the 4B routed 41 of its messages wrong. The 95% interval runs from 15.0% to 26.5%, from 2,000 resamples of messages.

For one day of 200 messages that interval is wide, and the rate should be read with it. Of the wrong routes, 18 were fallback replies to scenarios that needed a tool or an article. The rest went to a tool route.

The routes differ a great deal. Of the messages whose scenario belongs to the messages route, 10 of 17 were wrong, and every one of them was a fallback reply. Calendar was the other large case: 16 of 42 were wrong.

The fallback scenarios show the opposite error. They went to a tool route 11 times, out of 82. The alarms and lists routes had no wrong routes at all, but with 6 and 7 messages, those zeros say little.

The model-swap release routed 83 of 200 messages wrong, and 68 of those were fallback replies to scenarios that needed a tool or an article. The two releases answer the same 200 messages. Its prompt also carries `/no_think`, so the difference from the 4B is the smaller model and the suffix together.

Example `figure-failure-modes-by-route` (Python 3.13.16 · bm25s 0.3.16 · matplotlib 3.11.2 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Draw, for each scenario route on baseline day 1, how many of its messages the router sent right, to another tool route,
or to the fallback reply. The failing modes are coloured; the modes with no count on this day (truncated replies,
malformed tool calls) are printed as zero and named in the caption. Every value the figure draws is printed first."""
from lib.dayrun import run_day_traced
from lib.figures import ACCENT, INK, MUTED, new_figure, save
from lib.report import fmt_int

traced = run_day_traced("2026-12-08", live=False)  # the 4B's real replies, replayed from the recording
runs = traced.runs
malformed = sum(run.outcome.malformed_tool_calls for run in runs)  # calls the parser rejected
truncated = sum("length" in row["attributes"]["gen_ai.response.finish_reasons"]  # replies cut at the cap
                for row in traced.spans if row["name"].startswith("chat"))
assert malformed == 0 and truncated == 0
rows = []
for route in sorted({run.outcome.expected_route for run in runs}):
    group = [run for run in runs if run.outcome.expected_route == route]
    right = sum(run.outcome.route == route for run in group)
    fallback = sum(run.outcome.route == "fallback" and route != "fallback" for run in group)
    other = len(group) - right - fallback
    assert right + fallback + other == len(group)
    rows.append((route, len(group), right, other, fallback))
    print(f"route {route}, messages (n): {fmt_int(len(group))}")
    print(f"route {route}, routed right: {fmt_int(right)}")
    print(f"route {route}, wrong, to another tool route: {fmt_int(other)}")
    print(f"route {route}, wrong, to the fallback reply: {fmt_int(fallback)}")
print(f"truncated replies, baseline day 1: {fmt_int(truncated)}")
print(f"malformed tool calls, baseline day 1: {fmt_int(malformed)}")

fig, ax = new_figure(height=3.4)
ys = list(range(len(rows)))[::-1]  # the first route at the top
for y, (route, n, right, other, fallback) in zip(ys, rows):
    ax.barh(y, right, color=MUTED, alpha=0.35, label="routed right" if y == ys[0] else None)
    ax.barh(y, other, left=right, color=INK, label="wrong, to another tool route" if y == ys[0] else None)
    ax.barh(y, fallback, left=right + other, color=ACCENT, label="wrong, to the fallback reply" if y == ys[0] else None)
ax.set_xlim(0, 1.12 * max(right + other + fallback for _, _, right, other, fallback in rows))   # headroom so the longest bar is not clipped
ax.set_yticks(ys, [f"{route} (n = {n})" for route, n, *_ in rows])
ax.set_xlabel("messages on baseline day 1")
ax.legend(loc="lower right", frameon=False)
save(fig, "failure-modes-by-route")
```

Output:

```text
route alarms, messages (n): 6
route alarms, routed right: 6
route alarms, wrong, to another tool route: 0
route alarms, wrong, to the fallback reply: 0
route calendar, messages (n): 42
route calendar, routed right: 26
route calendar, wrong, to another tool route: 12
route calendar, wrong, to the fallback reply: 4
route devices, messages (n): 17
route devices, routed right: 16
route devices, wrong, to another tool route: 0
route devices, wrong, to the fallback reply: 1
route fallback, messages (n): 82
route fallback, routed right: 71
route fallback, wrong, to another tool route: 11
route fallback, wrong, to the fallback reply: 0
route lists, messages (n): 7
route lists, routed right: 7
route lists, wrong, to another tool route: 0
route lists, wrong, to the fallback reply: 0
route media, messages (n): 29
route media, routed right: 26
route media, wrong, to another tool route: 0
route media, wrong, to the fallback reply: 3
route messages, messages (n): 17
route messages, routed right: 7
route messages, wrong, to another tool route: 0
route messages, wrong, to the fallback reply: 10
truncated replies, baseline day 1: 0
malformed tool calls, baseline day 1: 0
figure: figures/failure-modes-by-route.svg
```

Figure 8.1 draws the same messages by route. Each bar is an expected route from the scenario table, and it holds that route's messages, split into the ones routed right, the ones wrong to another tool route, and the ones wrong to the fallback reply. Most wrong routes sit in the calendar, fallback and messages bars. Two modes count zero on this day, truncated replies and malformed tool calls, and the figure does not draw them. Chapter 7 counts the same day's messages by the route the assistant chose, not the expected one, so its counts differ: 7 messages and 31 media there, against 17 and 29 here.

*Figure 8.1. Each route's messages on baseline day 1: routed right, wrong to a tool route, or wrong to the fallback reply.*

![Horizontal bars for the seven routes on baseline day 1: most messages are routed right, and most wrong routes sit in the calendar, fallback and messages bars, with the fallback scenarios' misroutes going to tool routes](https://rollingedition.ai/books/observability-for-llm-applications/2026.11.2/figures/failure-modes-by-route.svg)

**Working rule:** Check each route against the scenario table on the trace, count fallback replies to other scenarios apart from the other wrong routes, and print every rate with its interval. Compare two releases only on the same messages, and name any suffix or prompt change beside the comparison.

## Querying each failure mode {#querying-each-failure-mode}

Each failure mode gets one query over the receiver's rows, and the receiver keeps each day in its own file. The baseline and the incident day are kept apart, so an injected row never sits in a real count. [The receiver](#the-book-receiver) holds the same rows the assistant's export writes, as chapter 5 shows.

Example `failure-modes-query` (Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""One query per failure mode over the stored rows: baseline day 1 (real) and the incident day (injected, labelled), each
kept in its own receiver file. The baseline's real failures are wrong routes and fallback replies; its span errors and
truncated replies print zero. A receiver holds spans only, so no query here counts a parse failure."""
import tempfile

from lib import query
from lib.dayrun import run_day_traced
from lib.export import write_jsonl
from lib.report import fmt_int

folder = tempfile.mkdtemp()
baseline = run_day_traced("2026-12-08", live=False)
write_jsonl(f"{folder}/baseline.jsonl", baseline.spans)
incident = run_day_traced("2026-12-09")  # live: the contacts server's rows go to the incident day's receiver
write_jsonl(f"{folder}/incident.jsonl", incident.spans + incident.server)
base, inc = query.connect(f"{folder}/baseline.jsonl"), query.connect(f"{folder}/incident.jsonl")

# A check event sits in the event list of its route span; the route the span chose is in the span's own attributes.
WRONG = """SELECT count(*) FROM spans, UNNEST(from_json(events, '["json"]')) AS t(e)
  WHERE json_extract_string(e, '$.name') = 'ambrewick.check'
  AND json_extract_string(e, '$.attributes."ambrewick.route.correct"') = 'false'"""
FALLBACK = """SELECT count(*) FROM spans, UNNEST(from_json(events, '["json"]')) AS t(e)
  WHERE json_extract_string(e, '$.name') = 'ambrewick.check'
  AND json_extract_string(e, '$.attributes."ambrewick.route.correct"') = 'false'
  AND json_extract_string(attributes, '$."ambrewick.route"') = 'fallback'
  AND json_extract_string(e, '$.attributes."ambrewick.route.expected"') != 'fallback'"""
TRUNCATED = """SELECT count(*) FROM spans WHERE name LIKE 'chat %'
  AND json_extract_string(attributes, '$."gen_ai.response.finish_reasons"') LIKE '%length%'"""
# Each error-result attempt joined to the contacts server's tools/call span in the same trace: one pair per injected error.
PAIRED = """SELECT count(*) FROM spans AS a JOIN spans AS s ON s.trace_id = a.trace_id
  WHERE a.name LIKE 'execute_tool %' AND s.name LIKE 'tools/call %'
  AND a.status = 'ERROR' AND json_extract_string(a.attributes, '$."error.type"') = 'tool_error'
  AND s.status = 'ERROR' AND json_extract_string(s.attributes, '$."error.type"') = 'tool_error'"""
# Errors on tool attempts and on the contacts server's spans, one row per span name and error.type, with a tie-break.
ERRORS = """SELECT name, json_extract_string(attributes, '$."error.type"') AS error_type, count(*) AS n FROM spans
  WHERE status = 'ERROR' AND (name LIKE 'execute_tool %' OR name LIKE 'tools/call %')
  GROUP BY name, error_type ORDER BY n DESC, name, error_type"""
REFUSED = """SELECT count(*) FROM spans WHERE json_extract_string(attributes, '$."error.type"') = 'RateLimitError'"""

def one(connection, sql):
    return connection.execute(sql).fetchone()[0]


print("wrong routes, baseline day 1 (real):", fmt_int(one(base, WRONG)))
print("wrong routes, incident day (real):", fmt_int(one(inc, WRONG)))
print("fallback replies to a scenario that is not fallback, baseline day 1 (real):", fmt_int(one(base, FALLBACK)))
print("truncated replies, baseline day 1 (real):", fmt_int(one(base, TRUNCATED)))
print("ERROR tool-attempt and server spans, baseline day 1 (real):", fmt_int(sum(n for *_, n in base.execute(ERRORS).fetchall())))
for name, error_type, n in inc.execute(ERRORS).fetchall():
    print(f"{name}, error.type {error_type}, incident day (injected): {fmt_int(n)}")
print("error-result attempts paired with their server span, incident day (injected):", fmt_int(one(inc, PAIRED)))
print("model requests refused, incident day (injected):", fmt_int(one(inc, REFUSED)))
```

Output:

```text
wrong routes, baseline day 1 (real): 41
wrong routes, incident day (real): 13
fallback replies to a scenario that is not fallback, baseline day 1 (real): 18
truncated replies, baseline day 1 (real): 0
ERROR tool-attempt and server spans, baseline day 1 (real): 0
execute_tool find_contact, error.type MCPError, incident day (injected): 4
execute_tool find_contact, error.type tool_error, incident day (injected): 3
tools/call find_contact, error.type tool_error, incident day (injected): 3
error-result attempts paired with their server span, incident day (injected): 3
model requests refused, incident day (injected): 47
```

The baseline's real failures come out as wrong routes, 41, and fallback replies to scenarios that needed a tool or an article, 18. The incident day's 13 wrong routes are real route choices by the model, not injected faults. The injected faults add none: a refused route attempt is retried on the same recorded reply, and a message that gives up has no check event to compare, so the injected windows add no wrong route. This chapter prints no rate for that day.

The other modes come out at zero on the baseline. Truncated replies: 0. The baseline has no cut reply, so this zero is untested here: the query has not been run on a day with the mode. Tool attempts and server spans with ERROR: 0. The true count of malformed tool calls on baseline day 1 is zero, counted from the replies in [the section on tool calls that do not parse](#tool-calls-that-do-not-parse), and the receiver holds nothing to query.

On the incident day, the same tool query finds the injected attempts: 4 timeouts on the attempt, 3 error results on the attempt, and 3 on the contacts server's span for the same calls. The refused model requests come to 47. Each of these is labelled injected in the output, and each sits in the incident day's file.

**Working rule:** Write one query for each failure mode, name the attribute or event it reads, and run it on a day that has the mode before you trust its zero. A query on an attribute that no span carries returns zero on every day, and that zero is a bug in the query, not a rate.

## Failures in production {#find-the-failure-in-production}

Production will not look like the incident day. The faults here are placed by the case, so each one can be matched to a window afterwards. A real fault has no label. A count by window is then a count of times that someone chose after the fact, and it is only as good as the record of the incident's start and end. Keep that record next to the counts, as the case's incidents file does, and say which counts came from it.

Other libraries will set status their own way. A client span can read ERROR with no `error.type`, as the MCP SDK's span does for a timeout in [the first table](#how-a-span-records-failure). Count failures by status first, and treat `error.type` as a label added to each count, not as a condition for being one. Retries inside a client library need care too. The openai client at 3.57.0 retries inside one call by default (`max_retries`), so instrumentation around that call writes one span, and the refusals it retried never become spans, so the span rule cannot count them. To see them, set `max_retries=0` and retry in your own code, as this book does.

Retries in your own code need attributes of their own. The HTTP conventions define `http.request.resend_count` for resent HTTP requests ([HTTP spans](https://raw.githubusercontent.com/open-telemetry/semantic-conventions/v1.45.0/docs/http/http-spans.md), v1.45.0). That attribute does not describe an MCP call, so this book's retry carries `ambrewick.attempt`. Choose an attribute that names the attempt in whatever protocol your call uses.

Finally, the span rule counts a message that recovered. A message whose first model request was refused and whose later request got a reply counts as an error, as [the retry section](#retries-under-a-timeout) shows. Chapter 10's gate counts the recovered message as an error. Chapter 9's objective counts what the user saw, so a message that got a reply after a retry is not a failure there ([service-level objectives](#service-level-objectives)). A message whose first tool attempt timed out and whose retry succeeded would count too. On the incident day that case did not occur, since the retries of both timed-out messages timed out as well. If the two numbers would tell different stories in your system, measure both, and print each with the rule that produced it.

**Working rule:** Before you publish a failure rate from production, print its count, the window it covers, and how many of its failures recovered. Name the error type for each kind of failure, and say which kinds carry no type at all. When the number is what users saw, count by message outcome, as chapter 9's objective does.

## What this chapter decided {#find-the-failure-decisions}

A failure is found at the span that records it, so each decision below names the span it reads.

- We define an error as a span with status ERROR, and we count a message by any of its spans. `error-status-by-step` prints the counts that rule gives, and `retries-under-incident` shows the message that recovered and still counts.
- We write the class name the package raises into `error.type`, or the conventions' value where one is defined, such as `tool_error` for an `isError` result. The registry has no value for a timeout or a 429. `error-status-by-step` shows the names, and `retries-under-incident` shows the timeouts.
- We keep the SDK's exception event rather than a log record, because the receiver holds spans and every query here reads them. [Chapter 4's timeout example](#errors-across-the-boundary) shows the event.
- We count each failed attempt as its own error, so the first timeout counts. `retries-under-incident` prints the timed-out attempts and the retries they led to.
- We read a cut reply and a wrong route as quality findings, not errors. `truncated-replies` and `wrong-routes-by-label` print both, with the cap and the scenario table beside them.
- We parse each reply for a tool call, because the finish reason cannot show one. `malformed-tool-calls` prints the parser's counts.
- We keep real and injected failures in separate rows and files, and we label every injected count. `failure-modes-query` reads two receivers, and `error-status-by-step` asserts that every ERROR span on the incident day carries the injected label.

# Set alerts on the assistant's metrics

By the end of this chapter you can set two alerts on a service's metrics, test each one on a normal day and on an incident day, and say what each one misses. On the incident day, lookups to the contacts team's server start timing out at 13:00 UTC. The 13 messages in the hour to 13:15 all got a reply, although both attempts of each lookup timed out. Beside that, the model's rate limit at 15:30 left 11 of 15 messages in its hour with no reply. Which of those numbers would wake someone, and would the same number wake someone on a normal day? The faults on the incident day were injected, at windows the case sets, so nothing below is a record of an outage or a measure of any real service.

The assistant is Ambrewick's back end, and it records its own metrics as it runs. An alert can read those metrics without reading a single span. A metric is cheap to keep for every minute of a day, because it holds a few numbers for each attribute set ([chapter 6](#totals-from-metrics-not-spans) defines the form) and not one record for each message. That trade has a cost, which the chapter measures as it goes: a metric can say how many messages failed, but not which ones, and not why.

## The metrics the assistant exports {#metrics-the-assistant-exports}

A trace answers what happened to one message. An alert needs a different kind of record: a number for each minute of the day that moves when many messages move. [Chapter 6](#totals-from-metrics-not-spans) defines the metric, counter and histogram that this chapter uses, and reads the token totals from them. This section sets out which instruments the assistant records and what each one counts.

The assistant has a meter, and the meter records each operation as the operation ends. There are three duration histograms, one for each kind of operation. A message is one `invoke_agent` operation, so `gen_ai.invoke_agent.duration` holds one point for each message. A model call is one `chat` operation, and `gen_ai.client.inference.duration` holds one point for each call attempt. A tool attempt is one `execute_tool` operation, and `gen_ai.execute_tool.duration` holds one point for each. The names and units come from the [GenAI conventions' metrics page](https://raw.githubusercontent.com/open-telemetry/semantic-conventions-genai/v0.1.0/docs/gen-ai/gen-ai-metrics.md), at version 0.1.0. The model-call and tool histograms are defined on the [client inference](https://raw.githubusercontent.com/open-telemetry/semantic-conventions-genai/v0.1.0/docs/gen-ai/client-inference.md) and [execute tool](https://raw.githubusercontent.com/open-telemetry/semantic-conventions-genai/v0.1.0/docs/gen-ai/execute-tool.md) pages that the same version publishes. Each duration histogram takes the unit of seconds, and the conventions ask that a failed operation set `error.type`. A message that got no reply therefore carries `error.type` on its point in the message histogram, and the alert counts on that attribute.

The meter also records each model call's tokens, in the counters and per-call histograms that chapter 6 reads. This chapter's alert does not use them, but the same meter writes them, so the export below includes them.

The meter is live. The alert reads it while the day runs, and each point reaches the meter when its operation ends. Each example in this chapter reads the meter in the same process that made the measurements. A production alert reads the same metrics once they leave the process, through whatever pipeline carries them, and that pipeline is outside this book.

Baseline day 1 is a normal day with no injected fault, so it is the right day to check that the meter agrees with the spans. The replay runs the day with the meter attached, and the export is then read back and set beside the spans' own counts.

Example `assistant-metrics-export` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""The metrics the assistant exports, from its live meter (chapter 9, `metrics-the-assistant-exports`).

The assistant records each operation as it ends: a message is one `invoke_agent` operation, a model call one `chat`, a
tool attempt one `execute_tool`, and each model call's tokens go to the token counters and histograms. The names and
units come from the pinned registry (lib.genai.METRICS). The export must not lose what the spans count, so the sums
are checked against the spans' own sums."""
from lib.dayrun import run_day_traced
from lib.genai import METRICS
from lib.metrics import DURATION, USAGE, make_alert_meter_provider, totals
from lib.report import fmt_int
from opentelemetry.sdk.metrics.export import InMemoryMetricReader

DAY = "2026-12-08"
reader = InMemoryMetricReader()
provider = make_alert_meter_provider(reader, service_instance_id=f"{DAY}-export")
traced = run_day_traced(DAY, live=False, meter_provider=provider)   # no faults on this day, so no live contacts server

reader.collect()
series = {}                                        # metric name: its number of series (one per attribute set)
for resource in reader.get_metrics_data().resource_metrics:
    for scope in resource.scope_metrics:
        for metric in scope.metrics:
            series[metric.name] = len(metric.data.data_points)
for name in sorted(series):
    print(f"series, {name}:", fmt_int(series[name]))
    print(f"unit, {name}:", METRICS[name]["unit"])

spans = lambda op: [row for row in traced.spans if row["attributes"].get("gen_ai.operation.name") == op]
messages, calls, attempts = spans("invoke_agent"), spans("chat"), spans("execute_tool")
print("messages, invoke_agent operations:", fmt_int(len(messages)))
print("model calls, chat operations:", fmt_int(len(calls)))
print("tool attempts, execute_tool operations:", fmt_int(len(attempts)))
sums = totals(reader)
print("input tokens, counter total:", fmt_int(int(sums[USAGE["input"]]["sum"])))
print("input tokens, summed over chat spans:", fmt_int(sum(c["attributes"]["gen_ai.usage.input_tokens"] for c in calls)))
print("message durations, histogram count:", fmt_int(sums[DURATION["invoke_agent"]]["count"]))

assert sums[DURATION["invoke_agent"]]["count"] == len(messages)     # one point per message, none lost
assert sums[DURATION["chat"]]["count"] == len(calls)                # one point per model call attempt
assert sums[DURATION["execute_tool"]]["count"] == len(attempts)     # one point per tool attempt
assert sums[USAGE["input"]]["sum"] == sum(c["attributes"]["gen_ai.usage.input_tokens"] for c in calls)
```

Output:

```text
series, gen_ai.client.inference.duration: 1
unit, gen_ai.client.inference.duration: s
series, gen_ai.client.inference.operation.input_tokens: 1
unit, gen_ai.client.inference.operation.input_tokens: {token}
series, gen_ai.client.inference.operation.output_tokens: 1
unit, gen_ai.client.inference.operation.output_tokens: {token}
series, gen_ai.client.inference.usage.cache_read.input_tokens: 1
unit, gen_ai.client.inference.usage.cache_read.input_tokens: {token}
series, gen_ai.client.inference.usage.input_tokens: 1
unit, gen_ai.client.inference.usage.input_tokens: {token}
series, gen_ai.client.inference.usage.output_tokens: 1
unit, gen_ai.client.inference.usage.output_tokens: {token}
series, gen_ai.execute_tool.duration: 1
unit, gen_ai.execute_tool.duration: s
series, gen_ai.invoke_agent.duration: 1
unit, gen_ai.invoke_agent.duration: s
messages, invoke_agent operations: 200
model calls, chat operations: 321
tool attempts, execute_tool operations: 10
input tokens, counter total: 104,811
input tokens, summed over chat spans: 104,811
message durations, histogram count: 200
```

The sentence to keep is that the export and the spans agree. The counter for input tokens totals 104,811 tokens, and the model calls' spans add up to the same 104,811. The message histogram holds one point for each message the day sent, 200 in all, and the example's assertions check that count against the spans. The histogram holds 1 series on this day, one attribute set for a normal message. The next section explains why that number is the one to watch.

**Working rule:** Take an alert's counts from the meter, which records each operation as it ends. Assert once, in a test, that the meter's sums equal the spans' sums, and after that query the metric every time the alert runs.

## Cardinality {#cardinality}

A metric is stored and queried one series at a time. Every distinct combination of attribute values opens a new series, and a dashboard draws one line for each. An attribute that takes a few values adds a few lines. An attribute that takes a new value for every user adds a line for every user, and that is the case the rest of this section examines.

A metric's **cardinality** is the number of distinct attribute combinations it is recorded with, each a series to store.

The meter keeps five attributes on each point, and no others: the error type, the agent's name, the operation's name, the [prompt version](#release-markers-in-the-spans) and the model's name. The conventions' registry lists these as the metric attributes, and the table below calls them the registry's attributes. So the live meter gives one series on a normal day, as [the previous section](#metrics-the-assistant-exports) printed. The two attributes an operator most often wants, the route and the user, are not on the meter's points. Adding each of them to the message histogram, from the spans of the same messages, shows what each would cost.

Example `cardinality-of-attributes` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Which attributes may label the assistant's duration metric (chapter 9, `cardinality`).

A metric keeps one series for each distinct set of attribute values, and each series is stored and queried. The
registry's attributes give one series for a message's operation on a normal day. A route gives a few more. A user ID
gives one series per user, so the count grows with the traffic and no dashboard can read it. The assistant's live meter
keeps the registry's attributes only, so its count is the first line. The other two are what the same messages would
give with another attribute added, counted from their spans."""
from lib.dayrun import run_day_traced
from lib.metrics import DURATION, METRIC_ATTRIBUTES, make_alert_meter_provider
from lib.report import fmt_int
from opentelemetry.sdk.metrics.export import InMemoryMetricReader

DAY = "2026-12-08"
reader = InMemoryMetricReader()
provider = make_alert_meter_provider(reader, service_instance_id=f"{DAY}-cardinality")
traced = run_day_traced(DAY, live=False, meter_provider=provider)  # the assistant's live meter, registry attributes only
messages = [row for row in traced.spans if row["attributes"].get("gen_ai.operation.name") == "invoke_agent"]
users = {row["attributes"]["ambrewick.user.id"] for row in messages}
routes = {row["attributes"]["ambrewick.route"] for row in messages if row["attributes"].get("ambrewick.route")}
print("messages:", fmt_int(len(messages)))
print("distinct users:", fmt_int(len(users)))
print("distinct routes:", fmt_int(len(routes)))


def series(reader, name: str | None = None) -> int:
    """The number of series a reader holds, for one metric when a name is given (one per distinct attribute set)."""
    reader.collect()
    return sum(len(metric.data.data_points) for resource in reader.get_metrics_data().resource_metrics
               for scope in resource.scope_metrics for metric in scope.metrics if name in (None, metric.name))


def series_with(extra: tuple[str, ...]) -> int:
    """The number of series the duration histogram holds when each message carries the registry's attributes and
    the `extra` ones. Values are the messages' real durations; only the count of attribute sets matters here."""
    own = InMemoryMetricReader()
    histogram = make_alert_meter_provider(own, service_instance_id=f"{DAY}-cardinality").get_meter("cardinality") \
        .create_histogram(DURATION["invoke_agent"], unit="s")
    for row in messages:
        attrs = row["attributes"]
        kept = {key: attrs[key] for key in METRIC_ATTRIBUTES + extra if key in attrs}
        histogram.record((row["end_ns"] - row["start_ns"]) / 1_000_000_000, kept)
    return series(own)


registry = series(reader, DURATION["invoke_agent"])
with_route = series_with(("ambrewick.route",))
with_user = series_with(("ambrewick.user.id",))
print("series, registry attributes:", fmt_int(registry))
print("series, registry attributes and route:", fmt_int(with_route))
print("series, registry attributes and user ID:", fmt_int(with_user))
assert registry == 1                       # on a normal day every message is a success with one attribute set
assert with_user == len(users)             # a user ID makes one series per user, and no two users share one
assert with_user > with_route > registry   # each attribute that varies multiplies the series
```

Output:

```text
messages: 200
distinct users: 121
distinct routes: 7
series, registry attributes: 1
series, registry attributes and route: 7
series, registry attributes and user ID: 121
```

The same 200 messages come from 121 distinct users, and they fall into 7 routes. The message histogram's series, for each set of attributes, are these.

| Attributes on the message histogram | Series |
| --- | --- |
| The registry's attributes | 1 |
| The registry's attributes and the route | 7 |
| The registry's attributes and the user ID | 121 |

A route adds a fixed, small number of lines, one for each of the 7 values the book uses. The user adds a line for each person who sent a message. The count grows with the users, and on a service with more of them it passes the SDK's limit, which the next paragraph describes.

The software has a limit as well. The OpenTelemetry metrics SDK stops at a default of 2,000 series for each metric stream in one collection cycle, and any attribute set past that limit falls into a single overflow series ([Metrics SDK, v1.45.0](https://raw.githubusercontent.com/open-telemetry/opentelemetry-specification/v1.45.0/specification/metrics/sdk.md)). The overflow series keeps the total right and hides the detail, so an operator who sees it has lost the lines that would have answered the question.

For that reason the assistant's metric takes no user ID, and this book never adds one. A user's messages are answered in traces, where one message is one record and its user is one attribute among many. A question about one user's latency is a question for a trace. The alert answers the question about the whole assistant's service.

**Working rule:** Label a metric only with values from a set you can list before launch. Count the series with each candidate attribute on a day of real traffic, and reject any attribute whose count grows with the users.

## Service-level objectives {#service-level-objectives}

An alert that says too many messages failed needs a line to measure them against, and a pace at which failing is still acceptable. An objective alone pages no one, so an alert measures how fast the failures use up the share that the objective leaves.

An **objective** is the share of messages that must succeed, or finish within a time, over a period; the **error budget** is the share it lets fail; the **burn rate** is how fast failures spend it, where 1 spends it exactly by the period's end.

The assistant has two objectives. The first is for failed messages. Over 30 days, 99% of messages must get a reply, which leaves an error budget of 1.0%; the period sets the arithmetic and forecasts no traffic. A message fails, for the objective, when its user got no reply; a retry that recovered is not a failure. That is narrower than [chapter 8's error](#how-a-span-records-failure). Under the span rule, a message whose first model request was refused and whose second request got a reply has an error, and so does a message whose lookup timed out on both attempts and whose model replied anyway. This objective counts neither, because the user got a reply in both cases. A [fallback reply](#where-the-time-went-in-twenty-messages) is a reply too, so the objective does not count it either. Whether a fallback reply went to the right scenario is a question for [chapter 8's wrong-route check](#wrong-routes-against-labels).

The second objective is for latency: over 30 days, 95% of messages must finish within 20 seconds, a line set above the slowest messages of a normal day, which leaves a latency budget of 5.0%. The number comes from the tail that [chapter 7](#tail-percentiles-with-intervals) measured on the recordings that [chapter 1](#replay-and-the-virtual-clock) introduces, so every time here is a recorded time on that replay's virtual clock. On baseline day 1 the 95th percentile (p95, by nearest rank) of message times is 18,351.2 ms, over 200 messages, which sits under the 20-second objective. The conventions advise edges for the `invoke_agent` duration histogram, as a SHOULD, from 0.1 to 86,400 s, which puts 12.8 and 25.6 either side of 20 and no edge at 20. The assistant's meter keeps its own edges, 0.5 to 60 s, set by a view, so the 20-second objective sits on one and the count within it is exact. [Chapter 7](#histogram-buckets-and-what-they-hide) shows what an estimate between two edges can do to a tail.

Baseline day 1 shows what the two objectives leave on a normal day.

Example `slo-and-budget` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""The assistant's two objectives, and the error budget each one leaves (chapter 9, `service-level-objectives`).

The error objective: 99% of messages get a reply. A message that ended with no reply has `error.type` on its duration
point, and it spends the budget. The latency objective: 95% of messages finish within 20 seconds, the book's edge
(chapter 7). The edge sits above baseline day 1's p95, so a normal day meets it. Both are read from the metrics that the
alert reads, on the same day. The 30-day period is the arithmetic's period, not a traffic forecast."""
from decimal import Decimal

from lib.dayrun import run_day_traced
from lib.metrics import DayMeter, burn_rate, tallies_by_tick
from lib.report import fmt_burn, fmt_int, fmt_ms, fmt_share
from lib.stats import nearest_rank

DAY = "2026-12-08"
ERROR_SLO, LATENCY_SLO, PERIOD_HOURS = 0.99, 0.95, 30 * 24
meter = DayMeter(DAY)                                  # the assistant's live meter, read after each message
traced = run_day_traced(DAY, live=False, meter_provider=meter.provider, after_message=meter.after)
day = tallies_by_tick(meter.marks, DAY)[-1][1]         # the last tick's cumulative tally is the whole day
durations = sorted(row["end_ns"] - row["start_ns"] for row in traced.spans
                   if row["attributes"].get("gen_ai.operation.name") == "invoke_agent")
p95 = nearest_rank(durations, 95)

print("error objective, share of messages with a reply:", fmt_share(round(ERROR_SLO * 100), 100))
print("error budget, share of messages that may fail:", fmt_share(round((1 - ERROR_SLO) * 100), 100))
print("latency objective, share of messages within 20 s:", fmt_share(round(LATENCY_SLO * 100), 100))
print("latency budget, share of messages that may run over 20 s:", fmt_share(round((1 - LATENCY_SLO) * 100), 100))
print("messages, baseline day 1:", fmt_int(day.requests))
print("messages with no reply:", fmt_int(day.failed), "of", fmt_int(day.requests))
print("messages within 20 s:", fmt_int(day.within), "of", fmt_int(day.requests), "share", fmt_share(day.within, day.requests))
print("messages over 20 s:", fmt_int(day.slow), "of", fmt_int(day.requests))
print("error budget spent over the day, burn:", fmt_burn(burn_rate(day.failed, day.requests, ERROR_SLO)))
print("latency budget spent over the day, burn:", fmt_burn(burn_rate(day.slow, day.requests, LATENCY_SLO)))
print("p95 of message times, nearest rank, n:", fmt_int(len(durations)), "messages")
print("p95 of message times:", fmt_ms(p95))
print("share of the 30-day budget a 1-hour page at burn 14.4 spends:", fmt_share(Decimal("14.4") * 1, PERIOD_HOURS))

assert day.failed == 0                               # a normal day has no message without a reply
assert day.within / day.requests >= LATENCY_SLO      # and meets the latency objective
assert p95 <= 20 * 1_000_000_000                     # the edge sits above the day's p95 (chapter 7, P-24)
```

Output:

```text
error objective, share of messages with a reply: 99.0%
error budget, share of messages that may fail: 1.0%
latency objective, share of messages within 20 s: 95.0%
latency budget, share of messages that may run over 20 s: 5.0%
messages, baseline day 1: 200
messages with no reply: 0 of 200
messages within 20 s: 194 of 200 share 97.0%
messages over 20 s: 6 of 200
error budget spent over the day, burn: 0.0
latency budget spent over the day, burn: 0.6
p95 of message times, nearest rank, n: 200 messages
p95 of message times: 18,351.2 ms
share of the 30-day budget a 1-hour page at burn 14.4 spends: 2.0%
```

Both objectives hold on the normal day, and the code asserts it. Of the day's messages, 0 of 200 got no reply, and 6 of 200 ran over 20 seconds.

Over the whole day the error burn is 0.0, and the latency burn is 0.6. Both sit below 1, which is the pace the objective allows. Those are the burns an alert would read on a quiet day, and the next sections use the same two objectives.

**Working rule:** Set each objective from the numbers of a normal day, and check that the normal day meets it before any alert reads it. Print the objective's error rule beside its count, so a reader can tell it from chapter 8's span rule.

## Burn rate {#burn-rate}

A burn rate is a speed, not a count. Fourteen failures mean little until you know how many messages they came from and how large the [error budget](#service-level-objectives) is. For a window, the burn rate is the window's failed share of messages divided by the error budget. The failed share is a count over a count, so the burn is one more division, and it is a number that can be compared across windows of different sizes.

The windows in this section are on virtual time. The one-hour window and the five-minute window are read at each five-minute tick of the day, and each window's count is the difference between two cumulative reads of the same histogram. A histogram only grows, so a window's messages are what the histogram added between the two reads. The example reads the meter after each message and adds the reads up for each tick. That is how a dashboard reads a rate from a counter that only grows while the process runs.

Run over the incident day's three injected windows, the example below treats each window as one fault: the contacts server's timeouts, the model's rate limit, and the contacts server's error replies. For each window it prints the messages in the hour up to the first tick after the window, how many of them got no reply, and the burns over the hour and over five minutes. The burns are the highest from the window to five minutes after it.

Example `burn-rate-by-window` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""The burn in each window on the incident day (chapter 9, `burn-rate`).

A burn rate is how fast a window spends the error budget. The windows are on virtual time: one hour (the long window)
and five minutes (the short one), each read as the difference between two cumulative reads of the metric at 5-minute
ticks. The live contacts server injects the three incident windows (lib.inject). The counts in each window are checked
against the spans' own counts, so the metric and the spans agree on what happened."""
from lib.clock import VirtualClock
from lib.dayrun import run_day_traced
from lib.inject import load_incidents
from lib.metrics import DayMeter, alert_verdicts, tallies_by_tick
from lib.report import fmt_burn, fmt_int

DAY, STEP_NS, HOUR_NS = "2026-12-09", 300 * 1_000_000_000, 3600 * 1_000_000_000
MIN_REQUESTS = 10                                     # a burn counts only over an hour with this many messages (alert)
meter = DayMeter(DAY)                                 # the assistant's live meter, read after each message
traced = run_day_traced(DAY, meter_provider=meter.provider, after_message=meter.after)  # live: faults on virtual time
midnight = VirtualClock(DAY).now_ns
tallies = tallies_by_tick(meter.marks, DAY)
errors = alert_verdicts(tallies, slo=0.99, measure="failed")   # objective 99%: budget 1%
slow = alert_verdicts(tallies, slo=0.95, measure="slow")       # objective 95% within 20 s: budget 5%
messages = [row for row in traced.spans if row["attributes"].get("gen_ai.operation.name") == "invoke_agent"]


def clock(ns: int) -> str:
    """A virtual time as hours, minutes and seconds UTC, from the day's midnight."""
    offset = (ns - midnight) // 1_000_000_000
    return f"{offset // 3600:02d}:{offset % 3600 // 60:02d}:{offset % 60:02d}"


for incident in load_incidents():
    first = -(-(incident.end_ns - midnight) // STEP_NS)     # the first tick at or after the window's end, 1-based
    error, latency = errors[first - 1], slow[first - 1]
    near = [v for v in errors if incident.start_ns < v.tick_ns <= incident.end_ns + STEP_NS]
    counted = {v.tick_ns for v in near if v.long.requests >= MIN_REQUESTS}   # the hours a page could read
    print(f"{incident.incident_id}, window:", f"{clock(incident.start_ns)} to {clock(incident.end_ns)} UTC")
    print(f"{incident.incident_id}, first tick after the window:", clock(error.tick_ns))
    print(f"{incident.incident_id}, messages in the hour to that tick:", fmt_int(error.long.requests))
    print(f"{incident.incident_id}, messages with no reply in that hour:", fmt_int(error.long.bad))
    print(f"{incident.incident_id}, error burn, 1 hour:", fmt_burn(error.long.burn))
    print(f"{incident.incident_id}, error burn, 1 hour, highest from the window to 5 minutes after it:",
          fmt_burn(max(v.long.burn for v in errors if v.tick_ns in counted)))
    print(f"{incident.incident_id}, error burn, 5 minutes, highest from the window to 5 minutes after it:",
          fmt_burn(max(v.short.burn for v in errors if v.tick_ns in counted)))
    print(f"{incident.incident_id}, messages over 20 s in that hour:", fmt_int(latency.long.bad))
    print(f"{incident.incident_id}, latency burn, 1 hour, highest from the window to 5 minutes after it:",
          fmt_burn(max(v.long.burn for v in slow if v.tick_ns in counted)))
    in_hour = [row for row in messages if error.tick_ns - HOUR_NS < row["end_ns"] <= error.tick_ns]
    assert len(in_hour) == error.long.requests                                              # the metric's count
    assert sum("error.type" in row["attributes"] for row in in_hour) == error.long.bad      # the spans' failures
```

Output:

```text
inc-contacts-timeout, window: 13:00:00 to 13:12:00 UTC
inc-contacts-timeout, first tick after the window: 13:15:00
inc-contacts-timeout, messages in the hour to that tick: 13
inc-contacts-timeout, messages with no reply in that hour: 0
inc-contacts-timeout, error burn, 1 hour: 0.0
inc-contacts-timeout, error burn, 1 hour, highest from the window to 5 minutes after it: 0.0
inc-contacts-timeout, error burn, 5 minutes, highest from the window to 5 minutes after it: 0.0
inc-contacts-timeout, messages over 20 s in that hour: 3
inc-contacts-timeout, latency burn, 1 hour, highest from the window to 5 minutes after it: 4.6
inc-rate-limit, window: 15:30:00 to 15:31:30 UTC
inc-rate-limit, first tick after the window: 15:35:00
inc-rate-limit, messages in the hour to that tick: 15
inc-rate-limit, messages with no reply in that hour: 11
inc-rate-limit, error burn, 1 hour: 73.3
inc-rate-limit, error burn, 1 hour, highest from the window to 5 minutes after it: 73.3
inc-rate-limit, error burn, 5 minutes, highest from the window to 5 minutes after it: 91.7
inc-rate-limit, messages over 20 s in that hour: 1
inc-rate-limit, latency burn, 1 hour, highest from the window to 5 minutes after it: 1.3
inc-mcp-error, window: 17:00:00 to 17:10:00 UTC
inc-mcp-error, first tick after the window: 17:10:00
inc-mcp-error, messages in the hour to that tick: 16
inc-mcp-error, messages with no reply in that hour: 0
inc-mcp-error, error burn, 1 hour: 0.0
inc-mcp-error, error burn, 1 hour, highest from the window to 5 minutes after it: 0.0
inc-mcp-error, error burn, 5 minutes, highest from the window to 5 minutes after it: 0.0
inc-mcp-error, messages over 20 s in that hour: 3
inc-mcp-error, latency burn, 1 hour, highest from the window to 5 minutes after it: 4.6
```

The tool attempts in those hours come from the meter's own tool histogram, `gen_ai.execute_tool.duration`, which the next example reads after each message in the same way.

Example `tool-attempts-by-window` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""The tool attempts in each incident window, read from the assistant's meter (chapter 9, `burn-rate-by-window`).

The meter records gen_ai.execute_tool.duration once for each tool attempt. The example reads that histogram after each
message, so a message's attempts count at its reply, as the alert's ticks do. For each incident window it prints the
attempts in the hour up to the first tick after the window, and how many carry error.type. The day's totals are checked
against the spans, so the meter and the spans agree on every attempt."""
from functools import reduce

from lib.clock import VirtualClock
from lib.dayrun import run_day_traced
from lib.inject import load_incidents
from lib.metrics import DURATION, DayMeter, Tally, tally
from lib.report import fmt_int

DAY, STEP_NS, HOUR_NS = "2026-12-09", 300 * 1_000_000_000, 3600 * 1_000_000_000
meter, tools, last = DayMeter(DAY), [], [Tally(0, 0, 0)]   # the live meter; attempts by reply time; the last read


def after_message(run) -> None:
    """Read the tool histogram after one message: the attempts it added, keyed by its reply time."""
    now = tally(meter.reader, DURATION["execute_tool"], 20)
    tools.append((run.replied_ns, now - last[0]))
    last[0] = now


traced = run_day_traced(DAY, meter_provider=meter.provider, after_message=after_message)  # live: faults on virtual time
midnight = VirtualClock(DAY).now_ns
calls = [row for row in traced.spans if row["attributes"].get("gen_ai.operation.name") == "execute_tool"]


def tools_in_hour(tick_ns: int) -> Tally:
    """The tool attempts of the messages that replied in the hour up to a tick."""
    return reduce(Tally.__add__, [added for replied, added in tools if tick_ns - HOUR_NS < replied <= tick_ns],
                  Tally(0, 0, 0))


for incident in load_incidents():
    tick = midnight + -(-(incident.end_ns - midnight) // STEP_NS) * STEP_NS    # the first tick after the window
    attempts = tools_in_hour(tick)
    print(f"{incident.incident_id}, tool attempts in the hour to that tick:", fmt_int(attempts.requests))
    print(f"{incident.incident_id}, tool attempts with error.type in that hour:", fmt_int(attempts.failed))

assert sum(added.requests for _, added in tools) == len(calls)                              # every attempt, as spans
assert sum(added.failed for _, added in tools) == sum("error.type" in row["attributes"] for row in calls)
```

Output:

```text
inc-contacts-timeout, tool attempts in the hour to that tick: 5
inc-contacts-timeout, tool attempts with error.type in that hour: 4
inc-rate-limit, tool attempts in the hour to that tick: 2
inc-rate-limit, tool attempts with error.type in that hour: 0
inc-mcp-error, tool attempts in the hour to that tick: 3
inc-mcp-error, tool attempts with error.type in that hour: 3
```

The table counts each window at the first tick after it, and its burns are the highest from the window to five minutes after it. The counts and the burns come from different ticks, so one row divided by another does not give the burn.

| Measure | Contacts timeout | Model rate limit | Contacts error replies |
| --- | --- | --- | --- |
| Window, UTC | 13:00:00 to 13:12:00 UTC | 15:30:00 to 15:31:30 UTC | 17:00:00 to 17:10:00 UTC |
| Messages in the hour to the first tick after | 13 | 15 | 16 |
| Of those, messages with no reply | 0 | 11 | 0 |
| Tool attempts in that hour | 5 | 2 | 3 |
| Of those, attempts with `error.type` | 4 | 0 | 3 |
| Highest error burn over 1 hour | 0.0 | 73.3 | 0.0 |
| Highest error burn over 5 minutes | 0.0 | 91.7 | 0.0 |
| Messages over 20 s in the hour | 3 | 1 | 3 |
| Highest latency burn over 1 hour | 4.6 | 1.3 | 4.6 |

Only the rate-limit window spends the error budget fast. Its hour holds 11 messages with no reply, and its error burn is 73.3 over the hour and 91.7 over five minutes. The injected rate limit refused those requests, and the refusals outlasted the retry backoff, so those messages ended with no reply.

The other two windows spend no error budget at all, because every message in them got a reply. Their latency burns, in the row for the highest latency burn over 1 hour, are well below 14.4, the burn the [next section](#an-alert-that-stays-quiet) pages at, and they measure slow messages, not failed ones.

The arithmetic gives the scale. A burn of 14.4 would spend the whole 30-day budget in 50 hours, since 720 hours divided by 14.4 is 50. At that pace one hour spends 2.0% of the month's budget, and the page threshold in the next section is 14.4 for that reason.

**Working rule:** Compute each window's burn from the counts inside that window, and print the count beside each burn. A reader who sees 0.0 needs to know whether it means no failures among many messages, or no messages at all.

## One page on the incident day, none on a quiet one {#an-alert-that-stays-quiet}

A burn-rate alert on one window is a poor alert. A long window fires only after the spend has piled up, and it keeps firing for as long as the long window holds the failures. A short window fires on a brief spike, and it clears as soon as the spike ends. The *Site Reliability Workbook* (O'Reilly, 2018) pairs the two in its chapter 5, "Alerting on SLOs", and its Table 5-8 gives a page at a burn of 14.4 over one hour, with a five-minute window for the short check ([the workbook](https://sre.google/workbook/alerting-on-slos/)). The table gives each burn by the share of budget it spends and the window alone, so 14.4 over an hour spends 2% of a 30-day budget. That holds for a 99% objective and for a 99.9% objective alike. Only the failed share that trips it changes, to 14.4% of messages here. The workbook's traffic is not this book's, so its 14.4 is a starting point here and not a measurement the book has made.

The workbook's method pairs slower windows as well: a page at burn 6 over 6 hours with a 30-minute short window, which spends 5% of the budget, and a ticket at burn 1 over 3 days with a 6-hour short window, which spends 10%. Those catch a slow, sustained burn that a one-hour pair misses. One day of traffic cannot test them, which is why this chapter sets only the 1-hour pair.

The book's alert pages when the error burn is at least 14.4 over the hour and at least 14.4 over the last five minutes, and when the hour holds at least 10 messages. The last condition is the book's own. With few messages in an hour, one failure moves the burn a long way, so an hour below the minimum cannot page. The long window makes the page need a sustained spend, the short window lets the page clear once the spend stops, and the minimum keeps both readings meaningful. The workbook has a section for traffic this thin, "Low-Traffic Services and Error Budget Alerting", whose own example is 10 requests an hour. It offers three options: generate artificial traffic, combine small services for monitoring, or change the product. The book's minimum is none of the three. In production we'd take the second: a service this small shares its objective with a larger one before anyone relies on its page.

Next, the alert runs over the incident day at every five-minute tick, for the [error objective](#service-level-objectives) and for the latency objective.

Example `alert-on-incident-day` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""The two-window burn-rate alert, run on the incident day at each 5-minute tick (chapter 9, `an-alert-that-stays-quiet`).

The page fires when the error budget burns at 14.4 or faster over the hour and over the last five minutes, and the hour
holds at least 10 messages, so one failed message in a quiet hour cannot page. 14.4 spends 2% of a 30-day budget in an
hour (chapter 9, `slo-and-budget`). The short window is what lets the page clear once the burn stops. The alert reads the
metric only. It is run for the error objective and for the latency objective, which has the same windows."""
from lib.clock import VirtualClock
from lib.dayrun import run_day_traced
from lib.inject import load_incidents
from lib.metrics import DayMeter, alert_verdicts, tallies_by_tick
from lib.report import fmt_burn, fmt_int

DAY, STEP_NS, THRESHOLD, MIN_REQUESTS = "2026-12-09", 300 * 1_000_000_000, 14.4, 10
meter = DayMeter(DAY)                                 # the assistant's live meter, read after each message
run_day_traced(DAY, meter_provider=meter.provider, after_message=meter.after)  # live: the contacts server injects faults
midnight = VirtualClock(DAY).now_ns
tallies = tallies_by_tick(meter.marks, DAY)
errors = alert_verdicts(tallies, slo=0.99, measure="failed", threshold=THRESHOLD, min_requests=MIN_REQUESTS)
slow = alert_verdicts(tallies, slo=0.95, measure="slow", threshold=THRESHOLD, min_requests=MIN_REQUESTS)


def clock(ns: int) -> str:
    """A virtual time as hours and minutes UTC, from the day's midnight."""
    offset = (ns - midnight) // 60_000_000_000
    return f"{offset // 60:02d}:{offset % 60:02d}"


pages = [v for v in errors if v.page]
cleared = next(v for v in errors if v.tick_ns > pages[0].tick_ns and not v.page)
print("page threshold, burn over 1 hour and over 5 minutes:", fmt_burn(THRESHOLD))
print("minimum messages in the hour:", fmt_int(MIN_REQUESTS))
print("ticks where the error page fires:", fmt_int(len(pages)), "of", fmt_int(len(errors)))
print("first tick the error page fires:", clock(pages[0].tick_ns))
print("messages in that hour, with no reply:", fmt_int(pages[0].long.bad), "of", fmt_int(pages[0].long.requests))
print("error burn at that tick, 1 hour and 5 minutes:", fmt_burn(pages[0].long.burn), fmt_burn(pages[0].short.burn))
print("first tick the error page is clear again:", clock(cleared.tick_ns))
print("ticks where the latency page fires:", fmt_int(sum(v.page for v in slow)))
print("highest latency burn over an hour, with the minimum met:",
      fmt_burn(max(v.long.burn for v in slow if v.long.requests >= MIN_REQUESTS)))

for incident in load_incidents():
    near = [v for v in errors if incident.start_ns < v.tick_ns <= incident.end_ns + STEP_NS]
    print(f"{incident.incident_id}, ticks in or just after the window:", fmt_int(len(near)))
    print(f"{incident.incident_id}, ticks where the error page fires:", fmt_int(sum(v.page for v in near)))

rate_limit = next(i for i in load_incidents() if i.kind == "rate-limit")
assert pages and all(rate_limit.start_ns < v.tick_ns <= rate_limit.end_ns + STEP_NS for v in pages)
assert sum(v.page for v in slow) == 0                  # the latency objective never pages on this day
for incident in load_incidents():
    if incident.kind != "rate-limit":
        assert not any(v.page for v in errors if incident.start_ns < v.tick_ns <= incident.end_ns + STEP_NS)
```

Output:

```text
page threshold, burn over 1 hour and over 5 minutes: 14.4
minimum messages in the hour: 10
ticks where the error page fires: 1 of 288
first tick the error page fires: 15:35
messages in that hour, with no reply: 11 of 15
error burn at that tick, 1 hour and 5 minutes: 73.3 91.7
first tick the error page is clear again: 15:40
ticks where the latency page fires: 0
highest latency burn over an hour, with the minimum met: 5.0
inc-contacts-timeout, ticks in or just after the window: 3
inc-contacts-timeout, ticks where the error page fires: 0
inc-rate-limit, ticks in or just after the window: 1
inc-rate-limit, ticks where the error page fires: 1
inc-mcp-error, ticks in or just after the window: 3
inc-mcp-error, ticks where the error page fires: 0
```

The alert pages once on the incident day. The first firing is at 15:35 UTC, and the page clears at 15:40. At the first firing the hour held 11 of 15 messages with no reply. Across the day the error page fires at 1 of 288 ticks, and the latency page never fires, as the example asserts.

The page fires for the rate-limit window and for nothing else. The timeout window never pages on this objective. It is the window the case starts at 13:00 UTC, and the error page fires at 0 ticks around it. Each lookup in that window was retried (2 retries), every attempt timed out (4 attempts), and no retry recovered. The model then wrote its reply from the tool's timed-out result. The two messages whose lookups timed out got replies that blamed the name, though the lookup never answered. Every message got a reply, so the error objective counts none.

The messages in that window go slow instead. Its latency burn reaches 4.6, and the highest latency burn over the whole day, with the minimum met, is 5.0. A latency page at 14.4 would need 72% of an hour's messages over 20 seconds, which is 14.4 times the 5.0% budget, and this day never came near that share. A fault the model answers around does not reach the error objective, and the latency objective would need a far larger share of slow messages before it paged. The fault shows in the tool's ERROR attempts, which the table's tool rows count in `gen_ai.execute_tool.duration`.

The contacts server's error replies, the third window, behave the same way on this objective, because the tool's error result went to the model, which answered with no retry (0 retries). Its messages got replies, and the error page fires at 0 ticks around that window.

Example `figure-burn-rate-incident-day` (Python 3.13.16 · bm25s 0.3.16 · matplotlib 3.11.2 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Draw the burn rate over the incident day, by window, with the page's threshold (chapter 9, `burn-rate-incident-day`).

A burn rate is a rate of budget use, not a count of errors: 14.4 means the window spends the budget 14.4 times as fast
as the objective allows. The one-hour burn is drawn as a gap wherever the hour holds fewer than the minimum of 10
messages, since a burn over two or three messages is noise. The five-minute burn is drawn as a gap wherever its window
holds no message, since a zero there would read as no failures among many. The page fires where the hour and the five
minutes both reach the threshold. The peaks are printed so a reader can find the spike on the figure."""
import math

from lib.clock import VirtualClock
from lib.dayrun import run_day_traced
from lib.figures import ACCENT, INK, MUTED, new_figure, save
from lib.metrics import DayMeter, alert_verdicts, tallies_by_tick
from lib.report import fmt_burn, fmt_int

DAY, THRESHOLD, MIN_REQUESTS = "2026-12-09", 14.4, 10
meter = DayMeter(DAY)                                 # the assistant's live meter, read after each message
run_day_traced(DAY, meter_provider=meter.provider, after_message=meter.after)  # live: faults on virtual time
tallies = tallies_by_tick(meter.marks, DAY)
errors = alert_verdicts(tallies, slo=0.99, measure="failed", threshold=THRESHOLD, min_requests=MIN_REQUESTS)
slow = alert_verdicts(tallies, slo=0.95, measure="slow", threshold=THRESHOLD, min_requests=MIN_REQUESTS)
hours = [(v.tick_ns - VirtualClock(DAY).now_ns) / 3_600_000_000_000 for v in errors]   # hours from the day's midnight
error_hour = [v.long.burn if v.long.requests >= MIN_REQUESTS else math.nan for v in errors]
error_five = [v.short.burn if v.short.requests else math.nan for v in errors]   # no message in five minutes: no burn
latency_hour = [v.long.burn if v.long.requests >= MIN_REQUESTS else math.nan for v in slow]


def peak(series):
    """The highest value of a series and the first tick that reaches it, as hours and minutes UTC."""
    known = [(x, i) for i, x in enumerate(series) if not math.isnan(x)]
    value = max(x for x, _ in known)
    index = min(i for x, i in known if x == value)     # the first tick at the peak, not the last
    minutes = round(hours[index] * 60)
    return fmt_burn(value), f"{minutes // 60:02d}:{minutes % 60:02d}"


print("gaps, one-hour burn at ticks under the minimum:", fmt_int(sum(math.isnan(x) for x in error_hour)))
print("peak error burn, 1 hour:", *peak(error_hour))
print("peak error burn, 5 minutes:", *peak(error_five))
print("peak latency burn, 1 hour:", *peak(latency_hour))
print("page threshold:", fmt_burn(THRESHOLD))

fig, ax = new_figure(height=2.8)
ax.plot(hours, error_hour, color=ACCENT, linewidth=1.8, label="error burn, 1 hour")
ax.plot(hours, error_five, color=INK, linewidth=1.2, marker="o", markersize=2.5, label="error burn, 5 minutes")
ax.plot(hours, latency_hour, color=MUTED, linewidth=1.2, linestyle="--", label="latency burn, 1 hour")
ax.axhline(THRESHOLD, color=INK, linewidth=1, linestyle=":", label="page threshold, 14.4")
ax.set_xlim(0, 24)
ax.set_xticks(range(0, 25, 3), [f"{h:02d}:00" for h in range(0, 25, 3)])
ax.set_ylim(0, 130)                                   # headroom above the 91.7 peak, for the legend
ax.set_yticks(range(0, 101, 20))
ax.set_ylabel("burn rate")
ax.legend(loc="upper left", ncol=2, frameon=False)    # in the headroom above the data, left of the 15:35 spike
save(fig, "burn-rate-incident-day")
```

Output:

```text
gaps, one-hour burn at ticks under the minimum: 253
peak error burn, 1 hour: 84.6 15:55
peak error burn, 5 minutes: 91.7 15:35
peak latency burn, 1 hour: 5.0 13:25
page threshold: 14.4
figure: figures/burn-rate-incident-day.svg
```

Figure 9.1 draws the incident day as an on-call dashboard would: one spike crosses the page threshold, in the rate-limit window, and nothing else comes near it. The error burn over 5 minutes peaks in that window and falls back within minutes, which is why the page clears. The error burn over 1 hour stays above the threshold for longer, because the refusals stay inside its hour after the five-minute burn has fallen. The latency burn over 1 hour never reaches the page threshold, 14.4. The one-hour lines have gaps where their hour holds fewer than the minimum, at 253 ticks of the day. The five-minute line has gaps where its window holds no message.

*Figure 9.1. Burn rate over the incident day, by window, with the page threshold of 14.4.*

![The five-minute error burn crosses the page threshold in the rate-limit window, and the latency burn stays well below it all day](https://rollingedition.ai/books/observability-for-llm-applications/2026.11.2/figures/burn-rate-incident-day.svg)

**Working rule:** Page only when a long window and a short window both reach the threshold, use the short window to clear the page, and let neither window page on an hour with fewer messages than the minimum.

## Test the same alert on a quiet day {#quiet-day-on-baseline-day-two}

A quiet day is the other half of the test. Baseline day 2 has no injected fault, and the same alert should not page on it at any tick, for either objective.

Example `alert-quiet-on-baseline-day-two` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""The same alert on baseline day 2, a normal day with no injected incident (chapter 9, `an-alert-that-stays-quiet`).

It is the alert's quiet day: the page must not fire at any tick, for either objective. The page is quiet here because no
message fails, not because of the hour's minimum. The day has 80 messages, so most hours hold fewer than the minimum,
and the printed count of the ticks that hold the minimum shows how little of the day the error page could read."""
from lib.dayrun import run_day_traced
from lib.metrics import DayMeter, alert_verdicts, tallies_by_tick
from lib.report import fmt_burn, fmt_int

DAY, THRESHOLD, MIN_REQUESTS = "2026-12-10", 14.4, 10
meter = DayMeter(DAY)                                 # the assistant's live meter, read after each message
run_day_traced(DAY, live=False, meter_provider=meter.provider, after_message=meter.after)  # no fault on this day
tallies = tallies_by_tick(meter.marks, DAY)
errors = alert_verdicts(tallies, slo=0.99, measure="failed", threshold=THRESHOLD, min_requests=MIN_REQUESTS)
slow = alert_verdicts(tallies, slo=0.95, measure="slow", threshold=THRESHOLD, min_requests=MIN_REQUESTS)
total = tallies[-1][1]

print("messages, baseline day 2:", fmt_int(total.requests))
print("messages with no reply:", fmt_int(total.failed))
print("messages over 20 s:", fmt_int(total.slow))
print("ticks where the hour holds the minimum:", fmt_int(sum(v.long.requests >= MIN_REQUESTS for v in errors)),
      "of", fmt_int(len(errors)))                     # the only ticks a full hour can page on this day
print("highest error burn over an hour:", fmt_burn(max(v.long.burn for v in errors)))
print("highest error burn over 5 minutes:", fmt_burn(max(v.short.burn for v in errors)))
print("highest latency burn over an hour, with the minimum met:",
      fmt_burn(max(v.long.burn for v in slow if v.long.requests >= MIN_REQUESTS)))
print("ticks where the error page fires:", fmt_int(sum(v.page for v in errors)))
print("ticks where the latency page fires:", fmt_int(sum(v.page for v in slow)))

assert total.failed == 0                               # no message on this day ended without a reply
assert not any(v.page for v in errors)                 # the error page stays quiet at every tick
assert not any(v.page for v in slow)                   # and so does the latency page
```

Output:

```text
messages, baseline day 2: 80
messages with no reply: 0
messages over 20 s: 4
ticks where the hour holds the minimum: 21 of 288
highest error burn over an hour: 0.0
highest error burn over 5 minutes: 0.0
highest latency burn over an hour, with the minimum met: 4.0
ticks where the error page fires: 0
ticks where the latency page fires: 0
```

Baseline day 2 has 80 messages, and 0 of them got no reply. Its highest error burn is 0.0 over the hour and 0.0 over five minutes.

Its highest latency burn, with the minimum met, is 4.0, well short of 14.4. The error page fires at 0 ticks, and the code asserts that the page is quiet at every one.

The quiet comes from the messages, not from the minimum. On this day's traffic only 21 of 288 ticks hold the minimum of messages in the hour, and those are the only ticks at which the error page could read a full hour at all. An hour under the minimum cannot page whatever it holds: nine failures out of nine stay silent. The minimum guards against a single failure in a thin hour, and on a thin day it decides most of the verdicts. Whether the alert is sound on a busier service is a question this book's traffic cannot answer.

**Working rule:** Test an alert on two days, one that must page and one that must not, and print the ticks it could not read beside the verdicts it gave.

## Where a burn-rate alert goes blind {#alerts-on-metrics-in-production}

An objective that counts what users got misses every fault the model answers around. In the [timeout window](#an-alert-that-stays-quiet), the model replied without the contact, and the page did not fire. A second objective is the usual answer: one on tool attempts, or one on the latency of the slowest messages by route. The examples in this chapter ship neither. A tool-level page would also read few calls on this traffic, since the meter counts every tool attempt, and baseline day 1 has only 10 of them in a whole day.

The alert sees a message only when the message ends. A message that waits on a retry enters the hour's count late, and its failure, if it has one, reaches the page late as well. An operator who expects the page to fire the moment a fault starts will be disappointed by every message that was still running at the tick.

Real faults carry no label. The windows in this chapter are the case's, so each count can be matched to a window afterwards. A production alert has no such record, and [chapter 8's production section](#find-the-failure-in-production) makes the same point about failure rates. Keep the incident's start and end next to the counts when you review them, and do not let a retrospective match stand as the measure of the alert.

The failed-message rate in this chapter and chapter 8's error rate disagree on purpose. The span rule in chapter 8 counts a recovered message as an error, and the objective here does not. Print both, each with the rule that produced it. Chapter 10's gate counts errors by span status, so chapter 8's error rate is the stricter one, and a release that looks bad to the gate may look fine to the objective. Neither number is wrong, because they answer different questions. A dashboard that shows one under the other's name will mislead.

Every new attribute on a metric multiplies its storage and its query time. Before you add one, count its series on a day of real traffic, as the cardinality example does, and keep the count with the change. The overflow series the SDK writes past its limit is not a fallback that keeps the metric useful. It is a sign that the attribute was the wrong one.

**Working rule:** Recompute the burn on your own traffic before the first page, and set the minimum from the messages an hour actually holds on your service.

## What this chapter decided {#alerts-on-metrics-decisions}

The chapter's lesson is that an objective on what users got pages on the faults users feel and misses the faults the model answers around, so an alert on the assistant's metrics needs a second number to see those.

- The error objective counts messages with no reply, read from the duration histogram. Span errors stay in the traces, under chapter 8's definition, and chapter 10's gate reads them.
- The latency objective is 95% of messages within 20 seconds, set from baseline day 1's tail and read at a bucket's edge.
- The page fires at a burn of 14.4 over one hour and over five minutes, with at least 10 messages in the hour. The pair and the starting number come from the workbook, and the minimum is the book's.
- The metrics carry the registry's attributes only. The route and the user are counted from the spans, to show what they would cost, and they stay out of the meter.
- No tool-level or per-route objective is set in this chapter, so the timeout window stays unpaged on this objective.
- An alert on what users got pages on the faults users feel, and it misses a fault the model answered around. A second objective, on the attempts or on the tail, is what would catch that fault. [Chapter 10's gate](#the-ci-gate) compares releases on message time, input tokens, cost, error rate and route accuracy, on the same messages, and it reads neither the attempts nor the tail.

# Catch a regression in the traces

By the end of this chapter you can say whether a release moved a number, by how much, and whether that move is bigger than the day's noise. You can also write the rule that stops a release from shipping when it moves too far. Four changes to the assistant wait to ship, and each claims to change nothing that matters. One adds six routing examples to the route prompt. One swaps the 4B model, Qwen3-4B-Instruct-2507, for the smaller Qwen3-0.6B. One retrieves more articles for the routes that retrieve, and one turns the prompt cache off. Which of them moved latency, tokens, cost, errors or route accuracy? And would a gate catch the ones that did, without stopping a normal day?

The question has two parts, and the second is the harder one. A release can move a number on the messages it was measured on and still sit inside what an ordinary day would show. So the comparison has to run both releases on the same messages, and it has to say how far the difference could move. The chapter builds a comparison of the two releases on the same messages, and turns it into a gate with fixed limits. It marks each trace with its release so a query can split them, pairs the releases message by message, and puts an interval beside every difference.

## Release markers in the spans {#release-markers-in-the-spans}

A comparison can only split traces by release if each trace says which release made it. Chapter 2 put the markers in place. The resource carries `service.version`, which names the release, and each inference span carries `gen_ai.prompt.version`, which names the prompt it was sent with ([who made the span](#who-made-the-span), and [the requirement levels](#requirement-levels), where the prompt pair appears). A release is marked by `service.version` on the resource and `gen_ai.prompt.version` on the inference span, so a query can split traces by release.

The marker does more than label. Without it, a query over a week of traces would mix the releases into one average, and no release would show its own movement. With it, the same query returns one row per release. Below, the same 60 messages are replayed under the baseline and under each of the four changes, and every span of the five replays goes into one file. Each replay keeps its own markers, and the span IDs come from one sequence, so no two replays share an ID.

Example `release-markers-query` (Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Replay the same 60 messages under each of the five releases, export every span to one store, and query the release
markers: the resource's service.version and the inference span's gen_ai.prompt.version. Each release's markers are the
only thing that tells its traces apart, so the query must give five distinct pairs. The span IDs come from one sequence,
so no two releases share an ID in the store."""
from lib.assistant import RELEASES
from lib.case import load_messages
from lib.export import write_jsonl
from lib.gate import release_spans
from lib.query import connect
from lib.report import fmt_int

import tempfile
from pathlib import Path

DAY = "2026-12-08"
FOLDERS = {"r0": "baseline-day-1", "r1": "release-prompt-v2", "r2": "release-model-swap",
           "r3": "release-top-8", "r4": "release-cache-off"}
PAIRED = {m.message_id for m in load_messages("2026-12-08-paired")}   # the 60 messages, in every release's recording
rows = release_spans(DAY, FOLDERS, PAIRED)
with tempfile.TemporaryDirectory() as folder:
    rows_file = Path(folder) / "spans.jsonl"     # the stored rows, as a file a query can read
    write_jsonl(rows_file, rows)
    db = connect(rows_file)
    markers = db.execute(
        "WITH inference AS (SELECT json_extract_string(resource, '$.\"service.version\"') AS version, "
        "json_extract_string(attributes, '$.\"gen_ai.prompt.version\"') AS prompt, "
        "json_extract_string(attributes, '$.\"gen_ai.prompt.name\"') AS name, trace_id FROM spans "
        "WHERE json_extract_string(attributes, '$.\"gen_ai.operation.name\"') = 'chat') "
        "SELECT version, prompt, name, count(*), count(DISTINCT trace_id) FROM inference "
        "GROUP BY version, prompt, name ORDER BY version, prompt, name").fetchall()
    per_version = db.execute(
        "SELECT json_extract_string(resource, '$.\"service.version\"') AS version, count(DISTINCT trace_id) "
        "FROM spans GROUP BY version ORDER BY version").fetchall()

for version, prompt, name, calls, traces in markers:
    print(f"service.version {version}, gen_ai.prompt.version {prompt}, {name}: {fmt_int(calls)} inference spans")
for version, traces in per_version:
    print(f"service.version {version}, messages (traces): {fmt_int(traces)}")
pairs = {(version, prompt) for version, prompt, _, _, _ in markers}
assert pairs == {(r.service_version, r.prompt_version) for r in RELEASES.values() if r.name in FOLDERS}
assert all(traces == len(PAIRED) for _, traces in per_version)   # every release answered every paired message
```

Output:

```text
service.version 1.0.0, gen_ai.prompt.version p1, ambrewick.answer: 33 inference spans
service.version 1.0.0, gen_ai.prompt.version p1, ambrewick.route: 60 inference spans
service.version 1.1.0, gen_ai.prompt.version p2, ambrewick.answer: 33 inference spans
service.version 1.1.0, gen_ai.prompt.version p2, ambrewick.route: 60 inference spans
service.version 1.2.0, gen_ai.prompt.version p1, ambrewick.answer: 16 inference spans
service.version 1.2.0, gen_ai.prompt.version p1, ambrewick.route: 60 inference spans
service.version 1.3.0, gen_ai.prompt.version p1, ambrewick.answer: 33 inference spans
service.version 1.3.0, gen_ai.prompt.version p1, ambrewick.route: 60 inference spans
service.version 1.4.0, gen_ai.prompt.version p1, ambrewick.answer: 33 inference spans
service.version 1.4.0, gen_ai.prompt.version p1, ambrewick.route: 60 inference spans
service.version 1.0.0, messages (traces): 60
service.version 1.1.0, messages (traces): 60
service.version 1.2.0, messages (traces): 60
service.version 1.3.0, messages (traces): 60
service.version 1.4.0, messages (traces): 60
```

The query groups the inference spans by their two markers and counts them, and it counts the traces each release produced. Every release answers the same 60 messages, which is why the trace counts match. The run asserts that the five marker pairs are exactly the pairs the release table gives, and that every release answered every message, so a missing marker fails the run rather than thinning a row.

Each release produced 60 traces, one per message. The table shows what the markers separate, and the answer calls are the count to check: the model swap is the row that differs from its neighbours.

| Release | Prompt version | Answer calls |
| --- | --- | --- |
| Baseline | p1 | 33 inference spans |
| Prompt change | p2 | 33 inference spans |
| Model swap | p1 | 16 inference spans |
| Top-8 release | p1 | 33 inference spans |
| Cache-off release | p1 | 33 inference spans |

Under the model swap there are fewer answer calls than under the baseline, on the same 60 messages. An answer call is the model call that writes the reply, and a message routed to fallback makes none. The model swap makes fewer of them because it routes more messages to fallback. [The CI gate](#the-ci-gate) counts the routes that changed later in this chapter. Without the markers the five rows would collapse into one, and nothing in the table would say which release made which call.

**Working rule:** Mark every trace with its release and its prompt version, and split each query by both before you read a number.

## Paired comparison on messages {#paired-comparison-on-messages}

Two releases measured on different messages differ for two reasons: the release, and the messages. A day's messages vary a great deal. Some are long requests, some route to the fallback reply, and some wait on a slow tool. Run both releases on the same messages and the second reason drops out of each difference, because each message serves as its own control. A paired comparison runs two releases on the same messages and summarises, for each message, the release's value minus the baseline's.

The method is the one that Evaluating LLM Applications calls a [paired comparison](https://rollingedition.com/concepts/artificial-intelligence/paired-comparison). That book subtracts verdicts; this one subtracts the values it reads from traces. Every latency here comes from the recording machine, a 4-vCPU Intel Xeon at 2.10 GHz, as chapter 1 describes, and the replays run on the virtual clock. Message time is the sum of the recorded durations of a message's model calls and contacts-tool calls, which is the number chapter 7 counts. The gaps the recorder left between calls are not in it.

Each measure has its own statistic. For message time, input tokens, cost, errors and [route accuracy](#wrong-routes-against-labels), the statistic is the mean of the per-message differences. The percentile is different, and the text says which statistic each difference is. For the 95th percentile, the book takes the difference of the two p95s, and it resamples the messages jointly: each resample draws the same messages for both releases and takes the 95th percentile on each side. The interval around every difference is chapter 7's percentile bootstrap, run on the messages and resampled as pairs. For a mean, the statistic is the mean of the per-message differences, and for the p95 it is the difference of the two p95s. The unit resampled is the message and never the span. Chapter 7 built that bootstrap for one release's percentile, and here the same resampling runs on pairs.

Input tokens here are the recorded counts, and [chapter 6](#three-token-counts) says where each count comes from.

Next, the example sets each change beside the baseline on the messages that change recorded.

Example `paired-latency-and-tokens` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Compare each release with baseline r0 on the same messages, in message time and input tokens: the mean of the per-message differences, and the p95 difference with the two p95s resampled jointly (PL-6). Each interval is a bootstrap of 2,000 resamples at 95 %, seed 20261207. The unpaired width for the input tokens is printed beside the paired one: the messages' own lengths cancel out of the paired difference."""
from lib.gate import measured, paired, paired_report

DAY, MODEL = "2026-12-08", "Qwen3-4B-Instruct-2507"
RELEASES_TO_COMPARE = [   # name, the release's recording folder, the model it ran
    ("r1", "release-prompt-v2", MODEL),       # p2: six routing examples in the route prompt
    ("r2", "release-model-swap", "Qwen3-0.6B"),
    ("r3", "release-top-8", MODEL),            # top 8 articles instead of 3
    ("r4", "release-cache-off", MODEL),        # a fresh state per call, so no cached prefix
]
base = measured("baseline-day-1", DAY, MODEL)  # r0, the cache on, on all 200 messages of baseline day 1
for name, folder, model in RELEASES_TO_COMPARE:
    _, before, after = paired(base, measured(folder, DAY, model))   # the messages this release recorded
    paired_report(name, before, after)
```

Output:

```text
r1, messages (paired with r0): 60
r1, r0 p95 message time on these messages: 17,128.2 ms
r1, message time, mean difference: 726.1 ms (95% interval 79.8 ms to 1,333.3 ms)
r1, message time, p95 difference: -345.3 ms (95% interval -495.9 ms to 2,301.0 ms)
r1, input tokens per message, mean difference: 90 (95% interval 70 to 115)
r1, input tokens, interval width paired: 45
r1, input tokens, interval width if unpaired: 276
r1, cost per 1,000 messages, mean difference: $0.006281 (95% interval $0.003197 to $0.009519)
r1, error rate, mean difference: +0.0% (95% interval +0.0% to +0.0%)
r1, route accuracy, mean difference: +3.3% (95% interval +0.0% to +8.3%)
r2, messages (paired with r0): 200
r2, r0 p95 message time on these messages: 18,351.2 ms
r2, message time, mean difference: -6,750.9 ms (95% interval -7,599.5 ms to -5,921.4 ms)
r2, message time, p95 difference: -14,109.1 ms (95% interval -16,749.8 ms to -12,105.6 ms)
r2, input tokens per message, mean difference: -200 (95% interval -258 to -148)
r2, input tokens, interval width paired: 110
r2, input tokens, interval width if unpaired: 137
r2, cost per 1,000 messages, mean difference: -$0.033156 (95% interval -$0.037326 to -$0.029012)
r2, error rate, mean difference: +0.0% (95% interval +0.0% to +0.0%)
r2, route accuracy, mean difference: -21.0% (95% interval -28.0% to -14.5%)
r3, messages (paired with r0): 60
r3, r0 p95 message time on these messages: 17,128.2 ms
r3, message time, mean difference: 2,222.5 ms (95% interval 1,099.6 ms to 3,462.8 ms)
r3, message time, p95 difference: 7,618.8 ms (95% interval 1,914.5 ms to 12,517.7 ms)
r3, input tokens per message, mean difference: 115 (95% interval 60 to 179)
r3, input tokens, interval width paired: 119
r3, input tokens, interval width if unpaired: 337
r3, cost per 1,000 messages, mean difference: $0.012542 (95% interval $0.006844 to $0.018909)
r3, error rate, mean difference: +0.0% (95% interval +0.0% to +0.0%)
r3, route accuracy, mean difference: +0.0% (95% interval +0.0% to +0.0%)
r4, messages (paired with r0): 60
r4, r0 p95 message time on these messages: 17,128.2 ms
r4, message time, mean difference: 2,881.5 ms (95% interval 2,209.1 ms to 3,677.3 ms)
r4, message time, p95 difference: 2,128.9 ms (95% interval 1,839.2 ms to 16,968.2 ms)
r4, input tokens per message, mean difference: 0 (95% interval 0 to 0)
r4, input tokens, interval width paired: 0
r4, input tokens, interval width if unpaired: 280
r4, cost per 1,000 messages, mean difference: $0.023233 (95% interval $0.018860 to $0.028303)
r4, error rate, mean difference: +0.0% (95% interval +0.0% to +0.0%)
r4, route accuracy, mean difference: +0.0% (95% interval +0.0% to +0.0%)
```

Pairing narrows the prompt change's token interval from 276 tokens wide to 45. On its 60 paired messages, input tokens per message rise by 90 (95% interval 70 to 115), and that rise is the change the gate has to see.

Its mean message time rises by 726.1 ms (95% interval 79.8 ms to 1,333.3 ms), and its 95th percentile moves the other way, by -345.3 ms (95% interval -495.9 ms to 2,301.0 ms). The mean and the p95 disagree in sign, and the p95's interval runs from below zero to far above it. On 60 messages the tail cannot say which way it moved. The p95 is printed here and not gated, and [what the gate misses](#what-the-gate-misses) says why.

Cost per 1,000 messages rises by $0.006281 (95% interval $0.003197 to $0.009519), priced at the book's price table, version `book-2026-11-02`, as [chapter 6](#the-price-table) sets out. The error rate does not move: +0.0% (95% interval +0.0% to +0.0%). The route accuracy difference is +3.3% (95% interval +0.0% to +8.3%). Its interval starts at zero, so this release has not been shown to change routing.

The model swap is the line with the most movement, and its comparison carries a caveat that applies to every line in it. The 0.6B's prompt carries `/no_think` as well as the smaller model, so the swap is not a pure model swap, as [prompt versions](#prompt-versions) explains. Its prompt version still reads p1. Mean message time changes by -6,750.9 ms (95% interval -7,599.5 ms to -5,921.4 ms). Route accuracy changes by -21.0% (95% interval -28.0% to -14.5%), and that change is the model and the suffix together. The swap ran all 200 messages of the baseline day. Its cost line rests on the 0.6B's row in the price table. The book wrote that row, and it has no source. The cost difference of -$0.033156 (95% interval -$0.037326 to -$0.029012) is therefore only as firm as that assumed rate.

The top-8 release retrieves more articles on the three routes that retrieve. [Chapter 7](#retrieved-context-against-prefill) measured the prefill that comes with the extra context. Here its input tokens rise by 115 (95% interval 60 to 179), and its mean message time by 2,222.5 ms (95% interval 1,099.6 ms to 3,462.8 ms).

The cache-off release is the one that should not move input tokens, and it does not. Its input total differs by 0 (95% interval 0 to 0), because the prompt the model reads is the same. Its cost rises by $0.023233 (95% interval $0.018860 to $0.028303), and its mean message time by 2,881.5 ms (95% interval 2,209.1 ms to 3,677.3 ms). The printed lines give the input total and the cost, not the cached count, so the cost line is the evidence here. [Chapter 6](#cached-prompt-tokens) explains how the cached count is derived.

Figure 10.1 draws the two differences for each release, the p95 message time on the left and input tokens per message on the right, each with its interval. The zero line is the reference. The prompt change's p95 interval crosses it, which is the tail's uncertainty in one picture. The token intervals for the prompt change, the model swap and the top-8 release lie clear of zero, and the cache-off release's token interval sits on it, as its input total says.

Example `figure-paired-differences` (Python 3.13.16 · bm25s 0.3.16 · matplotlib 3.11.2 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Draw each release's paired difference from baseline r0 on the same messages, in p95 message time and in input tokens per message, each with its interval. A line that crosses the zero line is a difference the interval cannot rule out; the p95 uses messages resampled jointly, and the token mean uses per-message differences."""
from lib.gate import P95, measured, paired
from lib.figures import ACCENT, INK, MUTED, new_figure, save
from lib.report import fmt_int, fmt_ms
from lib.stats import paired_interval, paired_mean_difference
from matplotlib.ticker import FuncFormatter

DAY, MODEL = "2026-12-08", "Qwen3-4B-Instruct-2507"
RELEASES_TO_DRAW = [   # name, the row's label as the prose gives it, the recording folder, the model; each against r0
    ("r1", "Prompt change", "release-prompt-v2", MODEL),
    ("r2", "Model swap", "release-model-swap", "Qwen3-0.6B"),
    ("r3", "Top-8 release", "release-top-8", MODEL),
    ("r4", "Cache-off release", "release-cache-off", MODEL),
]
def show(line, point, low, high, fmt):
    """Print one difference with its 95% interval."""
    print(line, fmt(round(point)), f"(interval {fmt(round(low))} to {fmt(round(high))})")

base = measured("baseline-day-1", DAY, MODEL)
fig, (left, right) = new_figure(height=3.2, columns=2, sharex=False)
ticks = []
for row, (name, label, folder, model) in zip(range(len(RELEASES_TO_DRAW))[::-1], RELEASES_TO_DRAW):   # the top row first
    ids, before, after = paired(base, measured(folder, DAY, model))
    time_p, (time_low, time_high) = paired_interval([m["time"] for m in before], [m["time"] for m in after], P95)
    token_p, (token_low, token_high) = paired_interval([m["tokens"] for m in before], [m["tokens"] for m in after],
                                                       paired_mean_difference)
    show(f"{name}, p95 message time, difference:", time_p, time_low, time_high, fmt_ms)
    show(f"{name}, input tokens per message, difference:", token_p, token_low, token_high, fmt_int)
    left.hlines(row, time_low / 1e6, time_high / 1e6, color=MUTED, linewidth=3)
    left.scatter([time_p / 1e6], [row], color=ACCENT, zorder=3)
    right.hlines(row, token_low, token_high, color=MUTED, linewidth=3)
    right.scatter([token_p], [row], color=ACCENT, zorder=3)
    ticks.append((row, f"{label} (n = {len(ids)})"))
for axis in (left, right):
    axis.axvline(0, color=INK, linewidth=0.8)            # no difference: a release that changed nothing
    axis.set_yticks(*zip(*ticks))
right.tick_params(axis="y", labelleft=False)          # the rows are named once, on the left
left.set_xlabel("difference in p95\nmessage time (ms)")
left.set_xticks([-10_000, 0, 10_000])
left.xaxis.set_major_formatter(FuncFormatter(lambda ms, _: f"{ms:,.0f}".replace("-", "−")))   # thousands separators
right.set_xlabel("mean difference in input\ntokens per message")
right.set_xticks([-200, 0, 200])
save(fig, "paired-differences")
```

Output:

```text
r1, p95 message time, difference: -345.3 ms (interval -495.9 ms to 2,301.0 ms)
r1, input tokens per message, difference: 90 (interval 70 to 115)
r2, p95 message time, difference: -14,109.1 ms (interval -16,749.8 ms to -12,105.6 ms)
r2, input tokens per message, difference: -200 (interval -258 to -148)
r3, p95 message time, difference: 7,618.8 ms (interval 1,914.5 ms to 12,517.7 ms)
r3, input tokens per message, difference: 115 (interval 60 to 179)
r4, p95 message time, difference: 2,128.9 ms (interval 1,839.2 ms to 16,968.2 ms)
r4, input tokens per message, difference: 0 (interval 0 to 0)
figure: figures/paired-differences.svg
```

*Figure 10.1. Each release's paired difference from the baseline with its 95% interval: p95 message time on the left, input tokens per message on the right.*

![Two panels, one row per release: the prompt change's p95 interval crosses the zero line, the cache-off release's token interval sits on it, and the other intervals lie clear of zero](https://rollingedition.ai/books/observability-for-llm-applications/2026.11.2/figures/paired-differences.svg)

**Working rule:** Subtract the baseline's value for each message before you summarise. Resample the messages jointly for a percentile, and print each difference with its count and its interval.

## Prompt versions {#prompt-versions}

The releases differ in their prompts, and one of them differs in its model as well, so this section says what changed in each prompt before the gate judges the numbers. The baseline's prompt is `p1`. The prompt change is `p2`, which adds six routing examples to the route prompt. The six examples add 86 tokens to every route call, and every message makes one. The rest of the prompt change's rise, 4 tokens per message, and the width of its paired interval come from the 2 messages whose route changed, as [the paired comparison](#paired-comparison-on-messages) shows. The markers confirm that both prompts make one route call per message, on the same 60 messages. The top-8 release keeps `p1`'s template, and only its retrieved context grows.

The model swap keeps `p1` as its prompt version, and this is the point to read carefully. Its prompt is not the baseline's, because it carries `/no_think`. Qwen3-0.6B is hybrid-thinking, and its [model card at the pinned commit](https://huggingface.co/Qwen/Qwen3-0.6B/blob/c1899de289a04d12100db370d81485cdf75e47ca/README.md) says that with thinking enabled the model always writes a `<think>...</think>` block, whose content may be empty when thinking is turned off. The recording script adds the suffix to the prompts. We decided that the release carries it, and that its prompt version stays `p1`. The release marker cannot show the suffix, so a query that splits by prompt version would count the model swap as the baseline's prompt. Under the suffix, the recording's model replies open with an empty block in 256 of their 257, and the assistant's parser drops that block from each reply. The pair still costs output tokens: on average, each route call's output grows by 4 tokens. One answer reply writes its reasoning into its block instead, and the parser drops that as well.

That matters for the token comparison. The two models share one Qwen3 tokenizer. The book checked that on three texts, and the 4B and the 0.6B give identical token IDs for each, so their input counts compare directly. The check covers three texts, not every message, and the chapter claims no more than that. The model swap's token difference is therefore the smaller model and the suffix together. The model-swap gate prints the split: the suffix adds 4 tokens to each route call, and the answer calls change it by -204 tokens per message, since the messages routed to fallback make no such call.

**Working rule:** Read a release's prompt version with the prompt's differences beside it. Say beside any model comparison whether the prompt changed as well.

## The CI gate {#the-ci-gate}

A comparison gives numbers, and a gate turns them into a decision. A regression gate is a check in CI that stops a release from merging when a number read from its traces has moved past its threshold, judged against its paired interval. A regression is a release's change that makes a trace-derived number worse than its limit allows, judged by the end of its interval nearest the limit. The limits are set below. The interval is the one [chapter 7](#tail-percentiles-with-intervals) builds for a number measured on a day's messages. [Evaluating LLM Applications](https://rollingedition.com/concepts/llm-evaluation/gate) shares that rule, a rule that stops a change from merging, and [Business Intelligence with Agents'](https://rollingedition.com/concepts/llm-evaluation/regression-gate) regression gate uses a different one. Evaluating LLM Applications also describes a [naive gate](https://rollingedition.com/concepts/llm-evaluation/naive-gate), which fails on the point estimate alone. This gate waits for the interval.

The gate has one job here: catch the prompt change without flagging the baseline's second day, with the same rules for both. The five rules are fixed in code, and the gate prints every line it judges. Message time, input tokens and cost may each rise by a tenth of the baseline's mean on the same messages, which is why the limits differ on 60 and 200 messages. The error rate may rise by two points, and route accuracy may fall by five points. Each rule reads the interval of the release's difference, and a rule flags a release when the end of that interval nearest the limit lies past the limit. For a rise, that is the lower end. For a fall in route accuracy, it is the upper end. So a flag means the release is worse than its limit, beyond its 95% interval. A release whose interval merely reaches past the limit is not flagged.

We set these limits, and the chapter applies them as printed rather than tuning them to these recordings. The relative limits scale with the baseline's mean. The error rate's baseline is zero, so a relative limit would leave it no room, and its limit is two points. Route accuracy is a share of messages, so it moves in points, and its limit is five. The rules read traces, never an answer's text. For route accuracy, the gate reads the route the reply names and checks it against the scenario table.

The error rule uses the definition [chapter 8](#how-a-span-records-failure) gives. A reply cut at its token cap, or a route reply that names no route, is not an error under that definition. Chapter 8 counts those as quality findings, and route accuracy already counts the second.

The gate has to pass a normal day, or a team would stop reading it. Gating baseline day 2 against day 1 shows whether it does, with the same rules and limits.

Example `gate-on-baseline-day-two` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Gate baseline day 2 against baseline day 1, both on release r0, with the same rules and limits as the prompt release's gate. The two days share no message, so each interval resamples each day on its own. The day is a normal day with no incident, and the gate must pass it, or a gate that flags every normal day would never reach CI."""
from lib.gate import judge, measured
from lib.report import fmt_int

DAY, MODEL = "2026-12-08", "Qwen3-4B-Instruct-2507"
before = measured("baseline-day-1", DAY, MODEL)            # r0 on all 200 messages of baseline day 1
after = measured("baseline-day-2", "2026-12-10", MODEL)    # r0 again, on 80 other messages, two days later
print("messages, baseline day 1:", fmt_int(len(before)))
print("messages, baseline day 2:", fmt_int(len(after)))
print("messages shared by the two days:", fmt_int(len(set(before) & set(after))))   # no message is in both
verdict, flagged = judge("baseline day 2 against day 1", list(before.values()), list(after.values()), paired=False)
assert verdict == "pass" and flagged == []     # the same release on a normal day must pass the same gate
```

Output:

```text
messages, baseline day 1: 200
messages, baseline day 2: 80
messages shared by the two days: 0
baseline day 2 against day 1, message time, mean: 168.8 ms, limit 801.9 ms (95% interval -1,599.0 ms to 1,895.0 ms)
baseline day 2 against day 1, message time, mean, flagged: no
baseline day 2 against day 1, input tokens per message, mean: -5, limit 52 (95% interval -108 to 99)
baseline day 2 against day 1, input tokens per message, mean, flagged: no
baseline day 2 against day 1, cost per message, mean, per 1,000 messages: $0.000545, limit $0.003781 (95% interval -$0.007950 to $0.008940)
baseline day 2 against day 1, cost per message, mean, flagged: no
baseline day 2 against day 1, error rate: +0.0%, limit +2.0% (95% interval +0.0% to +0.0%)
baseline day 2 against day 1, error rate, flagged: no
baseline day 2 against day 1, route accuracy: -3.3%, limit -5.0% (95% interval -14.5% to +7.8%)
baseline day 2 against day 1, route accuracy, flagged: no
baseline day 2 against day 1, gate verdict: pass
```

The two days share 0 messages, so the intervals are unpaired. Message time rises by 168.8 ms, limit 801.9 ms (95% interval -1,599.0 ms to 1,895.0 ms), and the lower end of that interval is far below the limit, so the rule does not flag. The other rules pass as well, and the verdict is pass.

Paired, the prompt change should fail on tokens; unpaired, the same 60 messages should pass. Both judgements run on the same messages, and the run asserts both results.

Example `gate-on-prompt-release` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Gate the prompt-change release r1 against r0 on the same 60 messages, with the gate's own rules. The gate reads the traces only: message time, input tokens, cost, errors and route accuracy. A rule flags a release when the end of its interval nearest the limit lies past the limit. The prompt change adds tokens to every route call, and the gate catches it only because the messages are paired: the same 60 messages judged as unrelated samples pass."""
from lib.gate import judge, measured, paired, tokens_by_step
from lib.report import fmt_int
from lib.stats import mean_of, paired_interval, paired_mean_difference

DAY, MODEL = "2026-12-08", "Qwen3-4B-Instruct-2507"
before = measured("baseline-day-1", DAY, MODEL)
after = measured("release-prompt-v2", DAY, MODEL)
ids, base, release = paired(before, after)      # the paired 60: r0 has every one of them
print("messages (paired):", fmt_int(len(ids)))
verdict, flagged = judge("r1 against r0", base, release, paired=True)
assert verdict == "fail" and flagged == ["input tokens per message, mean"]   # the prompt change, and only its tokens
assert "message time, mean" not in flagged   # its message time is not flagged: the interval's end stays under the limit
# The same 60 messages, judged as if they were two unrelated samples: the same release passes.
unpaired, unpaired_flagged = judge("r1 against r0, unpaired", base, release, paired=False)
assert unpaired == "pass" and unpaired_flagged == []   # without the pairing, the gate misses the change it must catch
steps0, steps1 = tokens_by_step("baseline-day-1", DAY, MODEL), tokens_by_step("release-prompt-v2", DAY, MODEL)
def change(steps, step):
    """r1 minus r0 in input tokens, for each message, in one step's calls; zero where the message made no such call."""
    return {i: steps[i].get(step, {"input": 0})["input"] - steps0[i].get(step, {"input": 0})["input"] for i in ids}
route_in, answer_in = change(steps1, "route"), change(steps1, "answer")
changed = {i for i in ids if before[i]["route"] != after[i]["route"]}
assert len(set(route_in.values())) == 1      # the six examples add the same tokens to every route call
assert all(answer_in[i] == 0 for i in ids if i not in changed)   # only a message whose route changed gets another answer call
route_share, answer_share = mean_of(list(route_in.values())), mean_of(list(answer_in.values()))
assert route_share + answer_share == mean_of([m["tokens"] for m in release]) - mean_of([m["tokens"] for m in base])
print("r1 against r0, route call input tokens per call, mean difference:", fmt_int(round(route_share)))
print("r1 against r0, messages whose route changed:", fmt_int(len(changed)))
print("r1 against r0, input tokens per message, answer calls' share:", fmt_int(round(answer_share)))
tokens_base, tokens_release = [m["tokens"] for m in base], [m["tokens"] for m in release]
_, (token_low, _) = paired_interval(tokens_base, tokens_release, paired_mean_difference)
print("r1 against r0, input tokens per message, low end of interval:", fmt_int(round(token_low)))
print("r1 against r0, input tokens per message, limit:", fmt_int(round(mean_of(tokens_base) / 10)))
```

Output:

```text
messages (paired): 60
r1 against r0, message time, mean: 726.1 ms, limit 737.3 ms (95% interval 79.8 ms to 1,333.3 ms)
r1 against r0, message time, mean, flagged: no
r1 against r0, input tokens per message, mean: 90, limit 49 (95% interval 70 to 115)
r1 against r0, input tokens per message, mean, flagged: yes
r1 against r0, cost per message, mean, per 1,000 messages: $0.006281, limit $0.003453 (95% interval $0.003197 to $0.009519)
r1 against r0, cost per message, mean, flagged: no
r1 against r0, error rate: +0.0%, limit +2.0% (95% interval +0.0% to +0.0%)
r1 against r0, error rate, flagged: no
r1 against r0, route accuracy: +3.3%, limit -5.0% (95% interval +0.0% to +8.3%)
r1 against r0, route accuracy, flagged: no
r1 against r0, gate verdict: fail
r1 against r0, unpaired, message time, mean: 726.1 ms, limit 737.3 ms (95% interval -1,627.6 ms to 3,141.5 ms)
r1 against r0, unpaired, message time, mean, flagged: no
r1 against r0, unpaired, input tokens per message, mean: 90, limit 49 (95% interval -45 to 231)
r1 against r0, unpaired, input tokens per message, mean, flagged: no
r1 against r0, unpaired, cost per message, mean, per 1,000 messages: $0.006281, limit $0.003453 (95% interval -$0.005244 to $0.018074)
r1 against r0, unpaired, cost per message, mean, flagged: no
r1 against r0, unpaired, error rate: +0.0%, limit +2.0% (95% interval +0.0% to +0.0%)
r1 against r0, unpaired, error rate, flagged: no
r1 against r0, unpaired, route accuracy: +3.3%, limit -5.0% (95% interval -10.0% to +16.7%)
r1 against r0, unpaired, route accuracy, flagged: no
r1 against r0, unpaired, gate verdict: pass
r1 against r0, route call input tokens per call, mean difference: 86
r1 against r0, messages whose route changed: 2
r1 against r0, input tokens per message, answer calls' share: 4
r1 against r0, input tokens per message, low end of interval: 70
r1 against r0, input tokens per message, limit: 49
```

The token rise clears its limit even at the low end of its interval: 70 tokens against a limit of 49. The rule flags, and the release's verdict is fail. The flag belongs to the input tokens alone.

Message time rises by 726.1 ms, limit 737.3 ms (95% interval 79.8 ms to 1,333.3 ms), which is under its limit, and the nearer end of its interval is under it too. The upper end runs past the limit, but the rule reads the end nearer the limit, so the rule does not flag. Cost rises by $0.006281, limit $0.003453 (95% interval $0.003197 to $0.009519) per 1,000 messages. Its lower end is under its limit, so cost is not flagged either, though tokens rise on the same messages.

Judged as unrelated samples, the same 60 messages pass. The token rise is still 90, limit 49 (95% interval -45 to 231), but its interval runs from below zero to above the limit, its nearer end is under the limit, and the verdict is pass. The interval widths in [the paired comparison](#paired-comparison-on-messages) are why. The shared messages hold the interval narrow enough to see the change through, and the unpaired interval is too wide to see it. The gate catches the change only because the messages are paired.

**Working rule:** Pair the releases whenever their messages overlap, and judge each rule on the end of its interval nearest the limit. Print every line, so a flag can be checked by eye.

## Gating the other changes {#gating-the-other-changes}

Gating the model swap on all 200 messages shows a different failure. Its amounts fall, which the rules pass, and its routes fall, which one rule catches.

Example `gate-on-model-swap` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Gate release r2, the 0.6B model swap, against r0 on the same 200 messages, with the same rules and limits. Its route accuracy falls, and the gate flags it. Its message time, input tokens and cost fall too, and the rules for those amounts pass a fall. The fall comes from the answer calls: r2 routes more messages to the fallback reply, which makes no answer call. The suffix adds a few tokens to every route call. The gate reads each message's route reply against the route its scenario gives, never an answer."""
from lib.gate import judge, measured, paired, tokens_by_step, to_decimal
from lib.report import fmt_int, fmt_ms, fmt_usd
from lib.stats import mean_of

DAY, MODEL, SWAP = "2026-12-08", "Qwen3-4B-Instruct-2507", "Qwen3-0.6B"
before = measured("baseline-day-1", DAY, MODEL)
after = measured("release-model-swap", DAY, SWAP)   # r2: the 0.6B model, on all 200 messages
ids, base, release = paired(before, after)
verdict, flagged = judge("r2 against r0", base, release, paired=True)
print("messages (paired):", fmt_int(len(ids)))
assert verdict == "fail" and flagged == ["route accuracy"]   # the model swap is caught on route accuracy alone

steps0, steps2 = tokens_by_step("baseline-day-1", DAY, MODEL), tokens_by_step("release-model-swap", DAY, SWAP)
def change(step, field):
    """r2 minus r0 for each message, in one step's calls; zero where the message made no such call."""
    return [steps2[i].get(step, {field: 0})[field] - steps0[i].get(step, {field: 0})[field] for i in ids]
answered0 = {i for i in ids if "answer" in steps0[i]}
answered2 = {i for i in ids if "answer" in steps2[i]}
print("messages answered by r0 and not by r2:", fmt_int(len(answered0 - answered2)))
print("messages answered by r2 and not by r0:", fmt_int(len(answered2 - answered0)))
route_in, answer_in = change("route", "input"), change("answer", "input")
assert len(set(route_in)) == 1                      # every route call grew by the same amount: the suffix's tokens
route_share, answer_share = mean_of(route_in), mean_of(answer_in)
assert route_share + answer_share == mean_of([m["tokens"] for m in release]) - mean_of([m["tokens"] for m in base])
print("r2 against r0, route call input tokens per call, mean difference:", fmt_int(round(route_share)))
print("r2 against r0, route call output tokens per call, mean difference:",
      fmt_int(round(mean_of(change("route", "output")))))
print("r2 against r0, input tokens per message, route calls' share:", fmt_int(round(route_share)))
print("r2 against r0, input tokens per message, answer calls' share:", fmt_int(round(answer_share)))
print("r2 against r0, message time, answer calls' share:", fmt_ms(round(mean_of(change("answer", "time")))))
print("r2 against r0, cost per 1,000 messages, answer calls' share:",
      fmt_usd(to_decimal(mean_of(change("answer", "cost")) * 1000)))
replies = [text for i in ids for step in steps2[i].values() for text in step["replies"]]
empty = [text for text in replies if text.startswith("<think>\n\n</think>")]
assert all(text.startswith("<think>") for text in replies)   # the 0.6B still writes its block under /no_think
print("r2, model replies:", fmt_int(len(replies)))
print("r2, model replies with an empty <think> block:", fmt_int(len(empty)))
print("r2, model replies with text in their <think> block:", fmt_int(len(replies) - len(empty)))
```

Output:

```text
r2 against r0, message time, mean: -6,750.9 ms, limit 801.9 ms (95% interval -7,599.5 ms to -5,921.4 ms)
r2 against r0, message time, mean, flagged: no
r2 against r0, input tokens per message, mean: -200, limit 52 (95% interval -258 to -148)
r2 against r0, input tokens per message, mean, flagged: no
r2 against r0, cost per message, mean, per 1,000 messages: -$0.033156, limit $0.003781 (95% interval -$0.037326 to -$0.029012)
r2 against r0, cost per message, mean, flagged: no
r2 against r0, error rate: +0.0%, limit +2.0% (95% interval +0.0% to +0.0%)
r2 against r0, error rate, flagged: no
r2 against r0, route accuracy: -21.0%, limit -5.0% (95% interval -28.0% to -14.5%)
r2 against r0, route accuracy, flagged: yes
r2 against r0, gate verdict: fail
messages (paired): 200
messages answered by r0 and not by r2: 59
messages answered by r2 and not by r0: 4
r2 against r0, route call input tokens per call, mean difference: 4
r2 against r0, route call output tokens per call, mean difference: 4
r2 against r0, input tokens per message, route calls' share: 4
r2 against r0, input tokens per message, answer calls' share: -204
r2 against r0, message time, answer calls' share: -5,706.8 ms
r2 against r0, cost per 1,000 messages, answer calls' share: -$0.027870
r2, model replies: 257
r2, model replies with an empty <think> block: 256
r2, model replies with text in their <think> block: 1
```

The amounts fall because the model swap leaves 59 messages without the answer call the baseline made. Those answer calls change the count by -204 tokens per message. The suffix adds 4 tokens to each route call, and the two together make the fall. The rules for those amounts flag a rise, so a fall passes them, and the gate's pass on them follows from its route failure, not from a cheaper model.

Route accuracy changes by -21.0%, limit -5.0% (95% interval -28.0% to -14.5%), and the upper end of its interval is past the limit, so that rule flags it and the release's verdict is fail. Choosing a smaller model is the subject of [Small Open Models](https://rollingedition.com/small-open-models/s/where-the-small-model-still-loses), which this chapter does not take up. The release is the 0.6B with `/no_think`, as [prompt versions](#prompt-versions) says, so the route change belongs to the model and the suffix together. The error rate does not move: +0.0%, limit +2.0% (95% interval +0.0% to +0.0%), which matches the other releases in this chapter.

The route check counts a route as wrong when it differs from the scenario table, and it does not read the answer that follows. A right route with a wrong answer passes this rule.

The top-8 release and the cache-off release get the same gate on the same 60 paired messages, and the example runs both.

Example `gate-on-retrieval-and-cache` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Gate the top-8 release r3 and the cache-off release r4 against r0, each on the same 60 paired messages, with the same rules and limits as the other gates. The top-8 release retrieves more articles, so its input tokens rise, and its time and cost rise with them. The cache-off release sends the same prompts, so its input total does not move, but its cost and time rise. The gate flags r3 on all three amounts and r4 on time and cost alone."""
from lib.gate import judge, measured, paired
from lib.report import fmt_int

DAY, MODEL = "2026-12-08", "Qwen3-4B-Instruct-2507"
before = measured("baseline-day-1", DAY, MODEL)
verdicts = {}
for name, folder in (("r3", "release-top-8"), ("r4", "release-cache-off")):
    ids, base, release = paired(before, measured(folder, DAY, MODEL))
    print(f"{name} against r0, messages (paired):", fmt_int(len(ids)))
    verdicts[name] = judge(f"{name} against r0", base, release, paired=True)
assert verdicts["r3"] == ("fail", ["message time, mean", "input tokens per message, mean", "cost per message, mean"])
assert verdicts["r4"] == ("fail", ["message time, mean", "cost per message, mean"])   # its input total does not move
```

Output:

```text
r3 against r0, messages (paired): 60
r3 against r0, message time, mean: 2,222.5 ms, limit 737.3 ms (95% interval 1,099.6 ms to 3,462.8 ms)
r3 against r0, message time, mean, flagged: yes
r3 against r0, input tokens per message, mean: 115, limit 49 (95% interval 60 to 179)
r3 against r0, input tokens per message, mean, flagged: yes
r3 against r0, cost per message, mean, per 1,000 messages: $0.012542, limit $0.003453 (95% interval $0.006844 to $0.018909)
r3 against r0, cost per message, mean, flagged: yes
r3 against r0, error rate: +0.0%, limit +2.0% (95% interval +0.0% to +0.0%)
r3 against r0, error rate, flagged: no
r3 against r0, route accuracy: +0.0%, limit -5.0% (95% interval +0.0% to +0.0%)
r3 against r0, route accuracy, flagged: no
r3 against r0, gate verdict: fail
r4 against r0, messages (paired): 60
r4 against r0, message time, mean: 2,881.5 ms, limit 737.3 ms (95% interval 2,209.1 ms to 3,677.3 ms)
r4 against r0, message time, mean, flagged: yes
r4 against r0, input tokens per message, mean: 0, limit 49 (95% interval 0 to 0)
r4 against r0, input tokens per message, mean, flagged: no
r4 against r0, cost per message, mean, per 1,000 messages: $0.023233, limit $0.003453 (95% interval $0.018860 to $0.028303)
r4 against r0, cost per message, mean, flagged: yes
r4 against r0, error rate: +0.0%, limit +2.0% (95% interval +0.0% to +0.0%)
r4 against r0, error rate, flagged: no
r4 against r0, route accuracy: +0.0%, limit -5.0% (95% interval +0.0% to +0.0%)
r4 against r0, route accuracy, flagged: no
r4 against r0, gate verdict: fail
```

Both releases fail. The top-8 release is caught on all three amounts, and its input tokens rise by 115, limit 49 (95% interval 60 to 179) per message. The cache-off release is caught on time and cost alone, because its input stays the same, and its cost rises by $0.023233, limit $0.003453 (95% interval $0.018860 to $0.028303) per 1,000 messages.

| Comparison | Messages | Verdict | Rule flagged |
| --- | --- | --- | --- |
| Baseline day 2 against day 1, unpaired | 80 | pass | None |
| Prompt change against baseline, paired | 60 | fail | Input tokens |
| Prompt change against baseline, unpaired | 60 | pass | None |
| Model swap against baseline, paired | 200 | fail | Route accuracy |
| Top-8 release against baseline, paired | 60 | fail | Message time, input tokens and cost |
| Cache-off release against baseline, paired | 60 | fail | Message time and cost |

Each of the four changes moved something the gate reads, and the gate flags each one: the prompt change through its tokens, the model swap through its routes, the top-8 release on all three amounts, and the cache-off release on time and cost. The normal day passes, and no release moved the error rate. That answers the question at the top of the chapter, with the rules the gate was given.

**Working rule:** Check each flagged rule against the amount it reads, and ask what in the release moved that amount.

## What the gate misses {#what-the-gate-misses}

A gate passes whatever it does not read. The five rules read message time, input tokens, cost, the error rate and route accuracy, and a release can change other things the gate never sees. Four of these matter in this chapter.

The first is quality. The gate reads traces, not answers. A release can route every message correctly, keep its tokens and its time, and still write worse replies, and this gate passes it. Judging a reply is a different job. Evaluating LLM Applications gives it a [code check](https://rollingedition.com/concepts/llm-evaluation/code-check), which reads a reply's text against the item's own reference answer. A regression in quality needs a check of that kind, run on the same messages with the same paired comparison, and this chapter does not run one. The book judges no answer's quality.

The second is the tail. The 95th percentile is printed and not gated. On the 60 paired messages the prompt change's p95 difference points down while its mean points up, and the p95's interval is much wider than the mean's, as [the paired comparison](#paired-comparison-on-messages) shows. The gate reads the mean because, on 60 messages, the mean's interval is the narrower of the two. A release whose tail grew could still pass this gate on its mean.

The third is the interval itself. A rule flags only when the end of the interval nearest the limit passes it, so a real rise can pass. The prompt change's message time is the example. Its mean sits under the limit, and its interval's upper end reaches past it. The gate cannot say whether that release moved time past its limit. It can only decline to flag it.

The fourth is the record. In production, two releases rarely meet the same messages, and comparing them on live traffic is the subject of Evaluating LLM Applications' [variants on traffic](https://rollingedition.com/evaluating-llm-applications/s/variants-on-traffic). Every release in this chapter is a replay of calls the book recorded, and a replay answers only the calls its recording holds. A change that sends different calls cannot be gated here, because nothing answers them. Two more gaps follow from the same place. The error rate of the prompt change changes by +0.0% (95% interval +0.0% to +0.0%), and the baseline's own count of ERROR spans on its replay is 0, the status that [chapter 8](#how-a-span-records-failure) explains. The error rule is in the gate, but these recordings do not trip it, so the chapter cannot show it catch an error. The cost lines rest on the book's price table. Chapter 6 says that a self-hosted model is billed by its machine and not by its tokens, so the dollar figures compare token prices and do not compare bills.

**Working rule:** Name in each gate's report what it does not read, beside its verdict, so a pass is not taken for a clean release.

## The decisions this chapter made {#catch-a-regression-decisions}

- The prompt change is gated on its 60 paired messages, the model swap on all 200, the top-8 and cache-off releases on their 60, and the normal day on two unpaired days. The paired messages are the ones the baseline and the release share.
- We set the limits; the error rule is chapter 8's. The chapter applies them as printed and does not tune them to these recordings.
- The 95th percentile is printed and not gated, and the gate judges the mean of message time.
- The model swap's amounts are split into the suffix and the answers it lost, and its route accuracy is the model and the suffix together. Its cost rests on a price row with no source, and the chapter says so beside the cost line.
- The gate reads recorded calls, not live traffic, so every verdict here describes the recordings.

A difference means little without its interval, and the same messages are what keep the interval narrow enough to read. On 60 paired messages the prompt change's token difference is visible. The same 60 judged unpaired would hide it. That is why the chapter pairs every comparison it can, and why a reader who copies this gate should keep the pairing before the limits: the same limits, judged unpaired, pass the prompt change.

**Working rule:** Read a difference only with its interval beside it, on the same messages, and with the gate's blind spots printed beside its verdict.

# Choose which traces to keep

By the end of this chapter you can choose which traces a backend keeps, say what each choice drops, and scale a total from the traces it kept, with an interval around the result. You'll write a rule that keeps the traces an engineer needs most, and check it against the incident day.

Ambrewick keeps one trace for every message, and [chapter 1](#one-message-one-trace) kept every one. At the book's scale of 200 messages a day, that is simple to manage. A service that answers messages all day writes far more, and a backend that holds every trace for a year pays for each of them. A sampler keeps some traces and drops the rest, so the decision that matters is which ones. The incident day shows the problem. Its errors are rare, and the engineer who opens the traces after an alert needs those errors and the slow messages more than any typical message. A sampler that picks traces without reading them keeps the rare ones at the same share as everything else.

This chapter builds the three kinds of decision that trace sampling makes, and the estimate a total needs when only some traces are kept. Here trace sampling means deciding which traces the backend keeps. It has nothing to do with token sampling, which chooses the next word a model writes. The examples run on two recorded days: baseline day 1, which has no injected faults, and the incident day from [chapter 9](#an-alert-that-stays-quiet). Both were recorded on the recording machine, a 4-vCPU Intel Xeon at 2.10 GHz, which ran Qwen3-4B-Instruct-2507, and both are replayed on the [virtual clock](#replay-and-the-virtual-clock).

## Head sampling decides before the trace runs {#head-sampling}

Head sampling decides whether to keep a trace when it starts, before any span has run. The kind this chapter uses keeps a fixed share by the trace ID, so it cannot know whether the message will fail and cannot aim at failures. The ratio is the share of traces kept, and the sample is keyed on the [trace ID](#one-message-one-trace).

The SDK's ratio sampler compares the trace ID with the ratio. It reads the low 64 bits of the trace ID as a number, and it keeps the trace when that number falls below the ratio's share of the whole range ([the sampler in the Python SDK](https://raw.githubusercontent.com/open-telemetry/opentelemetry-python/v1.45.2/opentelemetry-sdk/src/opentelemetry/sdk/trace/sampling.py), pinned here at 1.45.2). The decision depends on the ID alone, so every span of a trace agrees with the others, and the same trace gets the same answer on every run. The book's trace IDs count up from 1, and small counts all fall under any ratio above zero, so the book hashes each count to 128 bits before the sampler reads it. The specification deprecates `TraceIdRatioBased` in favour of `ProbabilitySampler`, which decides from the 56 bits of randomness that W3C Trace Context Level 2 specifies ([the trace SDK specification at v1.50.0](https://raw.githubusercontent.com/open-telemetry/opentelemetry-specification/v1.50.0/specification/trace/sdk.md)). The pinned SDK has no `ProbabilitySampler`, so the book uses the ratio sampler at the root.

The replay runs every message first and makes the head decision afterward. The decision is applied to the completed traces, and it is the same decision the assistant's own sampler would make at the source, because the trace ID alone settles it. The example's last lines check that claim: at each ratio it uses, a provider with the same sampler starts a root span for every trace ID of the day, and the example asserts that the two decisions agree.

Example `head-sample-ratio` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Head sampling on baseline day 1: the share of messages each ratio keeps, and the rule that a larger ratio keeps every
message a smaller one kept. The decision is the SDK's TraceIdRatioBased on each message's trace ID, as its root would
make it, so the same messages stay kept as the ratio grows. A live provider samples the same trace IDs at the source, and
the replayed and the live decisions must agree."""
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

from lib.dayrun import run_day_traced
from lib.prices import PriceTable
from lib.report import fmt_int, fmt_share
from lib.sampling import head_ratio, head_sample, live_provider, message_traces, only_messages

MODEL = "Qwen3-4B-Instruct-2507"
DAY = "2026-12-08"                                  # baseline day 1: no injected faults
RATIOS = (0.01, 0.1, 0.5, 1.0)                      # 1.0 keeps everything, the check that the ratio is read as a share
traces = only_messages(message_traces(run_day_traced(DAY, live=False).spans, DAY, MODEL, PriceTable()))
print("messages on baseline day 1, of all messages:", fmt_int(len(traces)))
kept = {}                                           # ratio -> the sequential trace IDs it keeps
for ratio in RATIOS:
    kept[ratio] = {t.seq for t in head_sample(traces, ratio)}
    print(f"messages kept at ratio {ratio}, of {len(traces)}:", fmt_int(len(kept[ratio])))
    print(f"share of messages kept at ratio {ratio}:", fmt_share(len(kept[ratio]), len(traces)))
    # The source's own decision: a provider with the same sampler makes one root per trace ID, counting from 1.
    provider = live_provider(head_ratio(ratio), InMemorySpanExporter())
    tracer = provider.get_tracer("ambrewick.assistant")
    live = set()
    for seq in range(1, len(traces) + 1):
        root = tracer.start_span("invoke_agent probe")
        if root.is_recording():
            live.add(seq)
        root.end()
    differ = len(live ^ kept[ratio])
    print(f"trace IDs where the replayed and the live decision differ at ratio {ratio}, of {len(traces)}:", fmt_int(differ))
    assert differ == 0
# A trace kept at a small ratio is kept at every larger one: the decision compares one fixed value with the ratio.
assert kept[0.01] <= kept[0.1] <= kept[0.5] <= kept[1.0]
assert len(kept[1.0]) == len(traces)
```

Output:

```text
messages on baseline day 1, of all messages: 200
messages kept at ratio 0.01, of 200: 5
share of messages kept at ratio 0.01: 2.5%
trace IDs where the replayed and the live decision differ at ratio 0.01, of 200: 0
messages kept at ratio 0.1, of 200: 21
share of messages kept at ratio 0.1: 10.5%
trace IDs where the replayed and the live decision differ at ratio 0.1, of 200: 0
messages kept at ratio 0.5, of 200: 96
share of messages kept at ratio 0.5: 48.0%
trace IDs where the replayed and the live decision differ at ratio 0.5, of 200: 0
messages kept at ratio 1.0, of 200: 200
share of messages kept at ratio 1.0: 100.0%
trace IDs where the replayed and the live decision differ at ratio 1.0, of 200: 0
```

A larger ratio keeps every message that a smaller one kept, and the example checks that first. At 0.1 the backend keeps 21 of the day's 200 messages. The ratio describes the share over many traces, and a single day can land a little above or below it, so the count is the day's and not the ratio's.

**Working rule:** Pick a head ratio only for traffic whose rare cases you can afford to lose. Run the ratio sampler at the root only, under `ParentBased`, and leave every other service on the default sampler or another parent-based one. The [trace SDK specification](https://raw.githubusercontent.com/open-telemetry/opentelemetry-specification/v1.50.0/specification/trace/sdk.md) recommends the ratio sampler "only for root spans", since different SDKs, and different versions of one SDK, can give inconsistent results for the same input. Print the kept share beside its count, as the example does, and never read the share as a count.

## Children follow the root's decision {#parent-based-sampling}

A trace crosses a process boundary, and the contacts server is the second process. [Chapter 4](#traceparent-in-meta) put the trace's identity into each request as `traceparent`, and one of that header's flags is the sampled flag (Trace Context Level 1, the version the book pins). Parent-based sampling makes each span follow its parent's decision. A root span asks the head sampler, and every span below it reads its parent's flag instead of running a ratio of its own. That matters across processes, because the server never sees the assistant's ratio, only the flag.

The contacts server sets no sampler of its own. Its tracer provider takes the SDK's default, with `OTEL_TRACES_SAMPLER` unset, which follows a remote parent's sampled flag: when the flag is set the server samples the span, and when it is not set the server drops it. The probe below turns the assistant's sampler on at the source, at a ratio of 0.5, and counts what the server records under each root.

Example `parent-based-follows-root` (Python 3.13.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""A parent-based sampler at the assistant decides each message's trace once, at its root, and the contacts server follows
that decision through the traceparent. The point rests on the server's count: no span reaches the receiver from a
trace the assistant did not sample."""
import json
import tempfile
from collections import Counter
from pathlib import Path

from opentelemetry import trace
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

from lib.clock import VirtualClock
from lib.report import fmt_int, fmt_share
from lib.sampling import head_ratio, live_provider
from lib.tools import LiveContacts

DAY, PROBES, RATIO = "2026-12-09", 40, 0.5
exporter = InMemorySpanExporter()
provider = live_provider(head_ratio(RATIO), exporter)  # the assistant's provider: its roots sampled at 0.5, children follow
trace.set_tracer_provider(provider)                    # the MCP client span is made by the process's global provider
tracer = provider.get_tracer("ambrewick.assistant")
recorded = {}                                          # trace ID -> whether the assistant's root was recorded
with tempfile.TemporaryDirectory() as folder:
    spans_file = Path(folder) / "contacts-spans.jsonl"  # the server writes here, and the file is read after it exits
    with LiveContacts(VirtualClock(DAY), spans_file) as contacts:
        for number in range(PROBES):
            with tracer.start_as_current_span(f"invoke_agent probe {number}") as root:
                recorded[format(root.get_span_context().trace_id, "032x")] = root.is_recording()
                contacts.find("U0028", "Ana")          # one tool call, inside this root, so its traceparent carries the root's flag
    server = [json.loads(line) for line in spans_file.read_text(encoding="utf-8").splitlines()]
per_trace = Counter(row["trace_id"] for row in server)
sampled = [t for t, yes in recorded.items() if yes]
unsampled = [t for t, yes in recorded.items() if not yes]
print("probes, one assistant root each:", fmt_int(PROBES))
print(f"roots sampled at ratio {RATIO}, of {PROBES}:", fmt_int(len(sampled)))
print(f"share of roots sampled at ratio {RATIO}:", fmt_share(len(sampled), PROBES))
print("contacts server spans under sampled roots:", fmt_int(sum(per_trace[t] for t in sampled)))
print("contacts server spans under unsampled roots:", fmt_int(sum(per_trace[t] for t in unsampled)))
print("unsampled roots with any server span, of the unsampled:", fmt_int(sum(per_trace[t] > 0 for t in unsampled)))
print("sampled roots with any server span, of the sampled:", fmt_int(sum(per_trace[t] > 0 for t in sampled)))
assert all(t in recorded for t in per_trace)  # every server span belongs to a probe's trace
assert not any(per_trace[t] for t in unsampled)     # the server records nothing for an unsampled trace
assert all(per_trace[t] for t in sampled)           # and everything for a sampled one
```

Output:

```text
probes, one assistant root each: 40
roots sampled at ratio 0.5, of 40: 19
share of roots sampled at ratio 0.5: 47.5%
contacts server spans under sampled roots: 39
contacts server spans under unsampled roots: 0
unsampled roots with any server span, of the unsampled: 0
sampled roots with any server span, of the sampled: 19
```

The contacts server made no decision of its own, so a trace was recorded on both sides or on neither. Under the unsampled roots the server recorded 0 spans. Of the 40 probe roots, the assistant sampled 19, and every one of those had server spans, which the example asserts.

**Working rule:** Sample at the root only, and leave every other service on the default sampler or another parent-based one. Two halves of one trace survive apart when another service runs its own ratio, algorithm or SDK version, since two identical samplers at one ratio agree. We would not give a server its own ratio.

## Tail sampling reads the whole trace {#tail-sampling}

Head sampling decides before the message runs, and the failure happens while it runs. Tail sampling decides once the whole trace is in, by what it holds. The rule in this chapter keeps three kinds of trace, in this order. It keeps a trace whose message has an error, in the sense [chapter 8](#how-a-span-records-failure) defines. It keeps a trace whose message ran past the latency objective from [chapter 9](#service-level-objectives), which is 20,000.0 ms. And it keeps a trace whose model calls cost more than the 99th percentile of baseline day 1, which is $0.000115 per message, the costly tail that [chapter 6](#the-expensive-tail) counts. Each kept trace is kept whole, with every span from both processes, and the rule stops once its span budget is spent.

The rule is this book's own code, `TailRule` in `lib/sampling.py`, and it runs at the receiver once a trace's root has arrived. In every trace of the incident day the root is the last span to end, so a trace is whole when its root arrives. That is by end time. Spans can arrive over a network in another order, so a receiver should also wait.

The rule reads each whole trace, so the errors it keeps are the ones it found, not the ones a ratio happened to pick. The timeout window is part of this count. [Chapter 9](#an-alert-that-stays-quiet) showed that a lookup timeout writes ERROR attempts while the user still gets a reply, so those messages have an error in chapter 8's sense. The engineer needs their cause even though no user complained, and the rule keeps them for that reason.

Before the first run, make a prediction. The incident day has messages with an error, and a 10% head sample decides for each of them before anything runs. Predict how many of those messages the head sample keeps: all of them, about a tenth of them, or none. Write the number down, then run the example.

Example `tail-rule-keeps-errors` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""The incident day's failed messages, kept by a 10 percent head sample and by the tail rule. A message failed when a span
in its trace ends with ERROR (chapter 8). The head sample decides before anything runs, so the count it keeps is chance;
the tail rule reads each whole trace and keeps every failed one. A detached root is judged as a trace of its own."""
from lib.clock import NS_PER_SECOND
from lib.dayrun import run_day_traced
from lib.prices import PriceTable
from lib.report import fmt_int, fmt_ms, fmt_share, fmt_usd
from lib.sampling import TailRule, head_sample, message_traces, only_messages
from lib.stats import nearest_rank

MODEL = "Qwen3-4B-Instruct-2507"
BASE, INCIDENT = "2026-12-08", "2026-12-09"
SLOW_NS = 20 * NS_PER_SECOND                        # chapter 9's latency objective: a message over 20 s is slow
price = PriceTable()
# The expensive threshold is baseline day 1's 99th percentile of message cost (nearest rank, PL-5): the incident is
# judged by the day before it, not by itself.
expensive = nearest_rank([t.cost for t in only_messages(message_traces(run_day_traced(BASE, live=False).spans, BASE, MODEL, price))], 99)
live = run_day_traced(INCIDENT)                     # live: the contacts server runs the injected faults over stdio
traces = message_traces(live.spans + live.server, INCIDENT, MODEL, price)  # each trace whole, the server's spans included
messages = only_messages(traces)
failed = [t for t in messages if t.error]
head = head_sample(messages, 0.1)
kept = TailRule(keep_error=True, slow_ns=SLOW_NS, expensive=expensive, budget=sum(len(t.rows) for t in traces)).keep(traces)
print("latency threshold, the 20 s objective:", fmt_ms(SLOW_NS))
print("cost threshold, baseline day 1's 99th percentile per message:", fmt_usd(expensive))
print("messages on the incident day:", fmt_int(len(messages)))
print("detached roots, traces of their own with no message, incident day:", fmt_int(len(traces) - len(messages)))
print("messages with an error, of all messages:", fmt_int(len(failed)))
print("share of messages with an error:", fmt_share(len(failed), len(messages)))
print(f"messages with an error kept by a 10% head sample, of {len(failed)}:", fmt_int(sum(t.error for t in head)))
print("share of messages with an error kept by a 10% head sample:", fmt_share(sum(t.error for t in head), len(failed)))
print(f"messages with an error kept by the tail rule, of {len(failed)}:", fmt_int(sum(t.seq in kept for t in failed)))
print("share of messages with an error kept by the tail rule:", fmt_share(sum(t.seq in kept for t in failed), len(failed)))
assert all(t.seq in kept for t in failed)           # the tail rule keeps every failed message
assert sum(t.error for t in head) < len(failed)     # the head sample loses most of them
assert all(max(r["end_ns"] for r in t.rows if r["parent_span_id"] is None) == max(r["end_ns"] for r in t.rows)
           for t in traces)                         # the root ends last, so a trace is whole when its root arrives (B-83)
```

Output:

```text
latency threshold, the 20 s objective: 20,000.0 ms
cost threshold, baseline day 1's 99th percentile per message: $0.000115
messages on the incident day: 60
detached roots, traces of their own with no message, incident day: 4
messages with an error, of all messages: 17
share of messages with an error: 28.3%
messages with an error kept by a 10% head sample, of 17: 2
share of messages with an error kept by a 10% head sample: 11.8%
messages with an error kept by the tail rule, of 17: 17
share of messages with an error kept by the tail rule: 100.0%
```

The incident day has 60 messages, and 17 of them have an error.

The head sample loses most of those errors. It keeps 2 of them, which is 11.8%. The guess of about a tenth came close here, but the head sample had no way to aim at the errors, so its count was a matter of chance.

The tail rule loses none. It keeps all 17 of them.

A rule that keeps every error can still cost too much, so the book's rule also takes a budget of spans for the day. Spans are what the backend stores, and a trace with many model calls holds many of them. Next, the rule is given a budget that the incident day cannot fit whole: 120 spans against a day of 276.

Example `tail-rule-span-budget` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""The tail rule under a span budget on the incident day: errors first, then the slowest messages, then the costliest, each
kept whole until the budget is spent. The budget of 120 spans is below the 127 the rule would keep with none, so it has
to drop something; the point rests on every error being kept and the slow message with no error being dropped."""
from lib.clock import NS_PER_SECOND
from lib.dayrun import run_day_traced
from lib.prices import PriceTable
from lib.report import fmt_int, fmt_ms, fmt_share
from lib.sampling import TailRule, message_traces, only_messages, retained_bytes
from lib.stats import nearest_rank

MODEL = "Qwen3-4B-Instruct-2507"
BASE, INCIDENT = "2026-12-08", "2026-12-09"
BUDGET, SLOW_NS = 120, 20 * NS_PER_SECOND
price = PriceTable()
base = only_messages(message_traces(run_day_traced(BASE, live=False).spans, BASE, MODEL, price))
expensive = nearest_rank([t.cost for t in base], 99)  # the baseline day's 99th percentile of cost, as in the last example
live = run_day_traced(INCIDENT)                     # live: the contacts server runs the injected faults over stdio
traces = message_traces(live.spans + live.server, INCIDENT, MODEL, price)  # each trace whole, the server's rows included
messages = only_messages(traces)
spans = sum(len(t.rows) for t in messages)
kept = TailRule(True, SLOW_NS, expensive, BUDGET).keep(traces)
no_budget = TailRule(True, SLOW_NS, expensive, sum(len(t.rows) for t in traces)).keep(traces)
kept_spans = sum(len(t.rows) for t in traces if t.seq in kept)
dropped = [t for t in messages if t.duration_ns > SLOW_NS and not t.error and t.seq not in kept]
print("spans in the incident day's messages:", fmt_int(spans))
print("spans in messages with an error:", fmt_int(sum(len(t.rows) for t in messages if t.error)))
print("span budget:", fmt_int(BUDGET))
print("spans the tail rule keeps with no budget, incident day:", fmt_int(sum(len(t.rows) for t in traces if t.seq in no_budget)))
print("spans kept under the budget, of all spans:", fmt_int(kept_spans))
print("share of spans kept under the budget:", fmt_share(kept_spans, spans))
for reason in ("error", "slow", "expensive"):
    print(f"messages kept for {reason}, under the budget:", fmt_int(sum(v == reason for v in kept.values())))
print("slow messages with no error, dropped for the budget:", fmt_int(len(dropped)))
print("time of the slowest message dropped for the budget:", fmt_ms(max(t.duration_ns for t in dropped)))
print("messages over the expensive threshold with no error or slow time, incident day:",
      fmt_int(sum(t.cost > expensive and not t.error and t.duration_ns <= SLOW_NS for t in messages)))
print("messages over the expensive threshold with no error or slow time, baseline day 1:",
      fmt_int(sum(t.cost > expensive and not t.error and t.duration_ns <= SLOW_NS for t in base)))
# Retention: bytes per message without content, in the JSON-lines export (capture is off until chapter 12).
per_message, kept_bytes, day_bytes = retained_bytes(base, messages, kept)
print("bytes per message without content, baseline day 1:", fmt_int(per_message))
print("bytes kept under the budget, of the incident day's bytes:", fmt_share(kept_bytes, day_bytes))
assert all(t.seq in kept for t in messages if t.error)  # the budget leaves every error in
assert kept_spans <= BUDGET
assert sum(len(t.rows) for t in traces if t.seq in no_budget) > BUDGET
```

Output:

```text
spans in the incident day's messages: 276
spans in messages with an error: 116
span budget: 120
spans the tail rule keeps with no budget, incident day: 127
spans kept under the budget, of all spans: 116
share of spans kept under the budget: 42.0%
messages kept for error, under the budget: 17
messages kept for slow, under the budget: 0
messages kept for expensive, under the budget: 0
slow messages with no error, dropped for the budget: 1
time of the slowest message dropped for the budget: 22,622.1 ms
messages over the expensive threshold with no error or slow time, incident day: 0
messages over the expensive threshold with no error or slow time, baseline day 1: 0
bytes per message without content, baseline day 1: 2,831
bytes kept under the budget, of the incident day's bytes: 42.6%
```

The budget keeps 116 spans, which is 42.0% of the day's. Those are the spans of the 17 messages with an error, and the rule keeps no slow message and no costly one.

Errors are ranked first, so they take their spans before anything else is considered, and the remainder of the budget is what is left for a slow message. The slow message without an error, which took 22,622.1 ms, holds more spans than that remainder, so the budget drops it. Two assertions in the code hold the rule to this: every error is kept, and the budget binds, since with no budget the rule keeps 127 spans, more than the budget allows.

The budget of 120 spans is the book's choice, not a rule of the method. It is above the spans that the errors take, so every error survives. The messages with an error hold 116 spans between them, so a budget below that would drop one of them, and the rule exists to keep them. A larger budget would also keep the slow message, at the cost of its spans.

The expensive class keeps nothing extra on either day. The number of messages above the expensive threshold with neither an error nor a slow time is 0 on the incident day and 0 on baseline day 1. Every costly message on both recorded days was also an error or a slow message, so the class does no work on them. We keep it in the rule because a costly message with neither mark is possible, and the rule should keep it when one comes. Neither recorded day shows one. The errors this rule keeps are also the traces that chapter 12 scans for personal data, so the rule also decides what that scan reads.

**Working rule:** Keep errors first, and set the budget above the spans they take on a day you have measured, not from a guess. Count the messages that are costly but neither erroneous nor slow before you trust a cost class, and say what a smaller budget would drop.

## Estimate the day's totals from a sample {#estimating-totals-from-a-sample}

Sampling thins spans, so a total summed from the kept spans is smaller than the day, and sampling does not thin the counters. [Chapter 6](#totals-from-metrics-not-spans) showed that summing spans double counts, so the book reads totals from the counters, which the assistant's meter adds to as each model call ends. [Chapter 9](#metrics-the-assistant-exports) reads its alerts from the same meter, so sampling never thins a total or an alert. An estimate from a sample is for a split that the counters cannot make, and a split is only as good as each part's kept count.

Scaling a head sample's total by the inverse of its ratio estimates the whole, because every trace has the same chance of being kept: the kept total, times the inverse of the ratio, estimates the day. The interval is the estimate plus or minus 1.96 standard errors, with the standard error taken from the sampled traces alone. A tail rule keeps some traces whatever the ratio, so its kept set is not a fixed share of the day. Once the head ratio and the tail rule run together ([the decisions below](#choose-what-to-keep-decisions)), the backend holds their union, which is not a head sample, so mark each trace with the reason it was kept and scale only the head sample's traces. This section scales head samples only.

Scaling one 10% sample of baseline day 1 by ten gives an estimate that can be set against the day's full count and against the token counter.

Example `estimate-totals-error` (Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Estimate baseline day 1's total tokens and cost from a 10 percent head sample, scaled by one over the ratio, with the 95
percent interval (the estimate plus or minus 1.96 standard errors). The estimate is set against the full count, summed over
every message, and against the token counter's total for the day. The point is coverage: over 2,000 independent samples the
interval holds the full count in only some of them, and the printed count says how many."""
from decimal import Decimal

from opentelemetry.sdk.metrics.export import InMemoryMetricReader

from lib.dayrun import RELEASE, run_day_traced
from lib.metrics import USAGE, make_meter_provider, totals
from lib.prices import PriceTable
from lib.report import fmt_int, fmt_share, fmt_usd
from lib.sampling import draws_holding, estimate_total, head_sample, message_traces, only_messages

MODEL = "Qwen3-4B-Instruct-2507"
DAY, RATIO, DRAWS, SEED = "2026-12-08", 0.1, 2000, 20261207  # SEED is PL-6's; each draw salts the trace IDs with its number
reader = InMemoryMetricReader()
provider = make_meter_provider(reader, service_instance_id=f"{DAY}-metrics", service_version=RELEASE.service_version)
traced = run_day_traced(DAY, live=False, meter_provider=provider)  # the assistant's live meter counts each call's tokens
traces = only_messages(message_traces(traced.spans, DAY, MODEL, PriceTable()))
counter = totals(reader)
counter_tokens = int(counter[USAGE["input"]]["sum"]) + int(counter[USAGE["output"]]["sum"])
sample = head_sample(traces, RATIO)
full_tokens = sum(t.tokens for t in traces)
full_cost = sum((t.cost for t in traces), Decimal(0))
print(f"messages kept at ratio {RATIO}, of {len(traces)}:", fmt_int(len(sample)))
tokens, tokens_interval = estimate_total([t.tokens for t in sample], RATIO)
print("full count of tokens, all messages:", fmt_int(full_tokens))
print("token counter total for the day, input plus output:", fmt_int(counter_tokens))
print(f"estimated tokens, ratio {RATIO}:", fmt_int(int(tokens)))
print("estimate as a share of the full count, tokens:", fmt_share(tokens, full_tokens))
print("interval as shares of the full count, tokens, low end:", fmt_share(tokens_interval[0], full_tokens))
print("interval as shares of the full count, tokens, high end:", fmt_share(tokens_interval[1], full_tokens))
cost, cost_interval = estimate_total([t.cost for t in sample], RATIO)
print("full cost of the day, Qwen3-4B-Instruct-2507 at the book's rates:", fmt_usd(full_cost))
print(f"estimated cost, ratio {RATIO}:", fmt_usd(cost))
print("estimate as a share of the full cost:", fmt_share(cost, full_cost))
print("interval as shares of the full cost, low end:", fmt_share(cost_interval[0], full_cost))
print("interval as shares of the full cost, high end:", fmt_share(cost_interval[1], full_cost))
assert counter_tokens == full_tokens          # the counter reads each call once, so it matches the root spans
print("samples of the same day, drawn independently:", fmt_int(DRAWS))
held_tokens, held_cost = draws_holding(traces, RATIO, DRAWS, SEED)
print(f"intervals that hold the full count, of {fmt_int(DRAWS)} samples at ratio {RATIO}, tokens:", fmt_int(held_tokens))
print(f"intervals that hold the full count, of {fmt_int(DRAWS)} samples at ratio {RATIO}, cost:", fmt_int(held_cost))
```

Output:

```text
messages kept at ratio 0.1, of 200: 21
full count of tokens, all messages: 109,807
token counter total for the day, input plus output: 109,807
estimated tokens, ratio 0.1: 98,090
estimate as a share of the full count, tokens: 89.3%
interval as shares of the full count, tokens, low end: 38.7%
interval as shares of the full count, tokens, high end: 140.0%
full cost of the day, Qwen3-4B-Instruct-2507 at the book's rates: $0.007563
estimated cost, ratio 0.1: $0.005524
estimate as a share of the full cost: 73.0%
interval as shares of the full cost, low end: 29.6%
interval as shares of the full cost, high end: 116.5%
samples of the same day, drawn independently: 2,000
intervals that hold the full count, of 2,000 samples at ratio 0.1, tokens: 1,843
intervals that hold the full count, of 2,000 samples at ratio 0.1, cost: 1,854
```

The estimate starts from the 10% head sample of baseline day 1, which keeps 21 of the day's messages, and scales their tokens by ten. The full count is 109,807 tokens, and the day's token counter, which [chapter 6](#totals-from-metrics-not-spans) reads for totals, adds up to the same figure: 109,807.

One sample gives one estimate, and the interval says where the day's full count could lie given how the sample was drawn. This interval is built from the sample's own standard error, and it is not [chapter 7's bootstrap interval](#tail-percentiles-with-intervals). The token estimate from that one sample is 98,090 tokens.

The 95% interval runs from 38.7% to 140.0% of the full count, and it is too wide to act on: a sample of 21 messages leaves the total anywhere across that range.

The interval is also short of its label. Of 2,000 samples of the same day, drawn independently, 1,843 have an interval that holds the full count, against the 95% the interval is built for.

The cost estimate is a separate sum over the same sample. It is $0.005524, against a full cost of $0.007563 for the day, priced at the book's table `book-2026-11-02`.

Its interval runs from 29.6% to 116.5% of the full cost, and 1,854 of the same samples hold it.

Varying the ratio shows how the error depends on how much is kept.

Example `figure-sampling-error-by-ratio` (Python 3.13.16 · bm25s 0.3.16 · matplotlib 3.11.2 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""Draw the error of a head sample's estimate of baseline day 1's total tokens against the sampling ratio, with the 95 percent
interval (chapter 11, `estimating-totals-from-a-sample`). The interval narrows as the ratio rises, and at ratio 1.0 every message
is kept, so the interval has no width. The points the prose names are printed, so a reader can read them off the lines."""
import math

from lib.dayrun import run_day_traced
from lib.figures import ACCENT, INK, MUTED, new_figure, save
from lib.prices import PriceTable
from lib.report import fmt_int, fmt_share
from lib.sampling import estimate_total, head_sample, message_traces, only_messages

MODEL = "Qwen3-4B-Instruct-2507"
DAY = "2026-12-08"
RATIOS = (0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.5, 1.0)
traces = only_messages(message_traces(run_day_traced(DAY, live=False).spans, DAY, MODEL, PriceTable()))
full = sum(t.tokens for t in traces)
points = []                                         # (ratio, estimate share, interval low share, interval high share)
for ratio in RATIOS:
    sample = head_sample(traces, ratio)
    estimate, (low, high) = estimate_total([t.tokens for t in sample], ratio)
    points.append((ratio, 100 * estimate / full, 100 * low / full, 100 * high / full))
    if ratio in (0.01, 0.1, 0.5):
        print(f"messages kept at ratio {ratio}, of {len(traces)}:", fmt_int(len(sample)))
        print(f"estimate as a share of the full count, ratio {ratio}:", fmt_share(estimate, full))
        print(f"interval low end as a share of the full count, ratio {ratio}:", fmt_share(low, full))
        print(f"interval high end as a share of the full count, ratio {ratio}:", fmt_share(high, full))
print("full count of tokens, all messages:", fmt_int(full))
xs, estimate_share, low, high = zip(*points)
fig, ax = new_figure(height=2.8)
ax.fill_between(xs, low, high, color=MUTED, alpha=0.35, linewidth=0, label="95% interval")
ax.plot(xs, estimate_share, color=ACCENT, linewidth=1.8, marker="o", markersize=3, label="estimate, head sample")
ax.axhline(100, color=INK, linewidth=1, linestyle=":", label="full count")
ax.set_xscale("log")
ax.set_xticks(RATIOS, [f"{r:g}" for r in RATIOS])
ax.set_xlabel("sampling ratio (log scale)")
ax.set_ylabel("estimate, % of full count")
bottom, top = float(min(low)), float(max(high))      # the axis starts at the lowest interval end, not at zero
pad = 0.1 * (top - bottom)
ax.set_ylim(bottom - pad, top + 2 * pad)            # headroom above the widest interval, where the legend sits
ax.legend(loc="upper right", ncol=3, frameon=False)
save(fig, "sampling-error-by-ratio")
assert all(math.isclose(p[1], 100) for p in points if p[0] == 1.0)   # at ratio 1 every message is kept, so no error
assert all(math.isclose(p[2], p[3]) for p in points if p[0] == 1.0)  # and the interval has no width
```

Output:

```text
messages kept at ratio 0.01, of 200: 5
estimate as a share of the full count, ratio 0.01: 251.5%
interval low end as a share of the full count, ratio 0.01: -4.4%
interval high end as a share of the full count, ratio 0.01: 507.5%
messages kept at ratio 0.1, of 200: 21
estimate as a share of the full count, ratio 0.1: 89.3%
interval low end as a share of the full count, ratio 0.1: 38.7%
interval high end as a share of the full count, ratio 0.1: 140.0%
messages kept at ratio 0.5, of 200: 96
estimate as a share of the full count, ratio 0.5: 97.5%
interval low end as a share of the full count, ratio 0.5: 79.4%
interval high end as a share of the full count, ratio 0.5: 115.5%
full count of tokens, all messages: 109,807
figure: figures/sampling-error-by-ratio.svg
```

Figure 11.1 draws the same estimate at eight ratios, and its band closes as the ratio reaches 1.0. At the left, 5 messages are kept, and the estimate is 251.5% of the full count. Its interval runs from -4.4% to 507.5%, so the low end falls below zero, where the normal approximation fails with so few kept traces.

At 0.1, 21 messages are kept, the estimate is 89.3% of the full count, and the interval runs from 38.7% to 140.0%.

Ratio 0.5 keeps 96 messages, and the estimate is 97.5% of the full count, with an interval from 79.4% to 115.5%. At ratio 1.0 every message is kept, so the estimate is exact and the interval has no width, which the example asserts.

*Figure 11.1. The token estimate from a head sample, as a share of the full count, at eight sampling ratios, with its 95% interval.*

![A line of the estimated token total, as a share of the full count, against the sampling ratio on a log scale, with a shaded 95% interval; the band narrows overall as the ratio rises and closes at ratio 1.0](https://rollingedition.ai/books/observability-for-llm-applications/2026.11.2/figures/sampling-error-by-ratio.svg)

The interval measures the sampling's chance on this one day. Whether another day would give the same total is a different question, and this interval does not answer it.

**Working rule:** Scale only the traces the head ratio kept, by the inverse of its ratio, print the interval beside the estimate, and check the estimate against the counter total for the same day when one exists. Use a sampled estimate only for a split that the counters cannot make, and never for a total the counters already hold.

## What a kept trace costs to hold {#retention}

Retention is how long the backend keeps each kind of telemetry. [Data Governance as Code](https://rollingedition.com/concepts/data-governance/retention) states the same idea for a platform's data: how long each kind of data is kept. This chapter applies it to telemetry only, and it sets no period. The period depends on how far back an engineer must look after an incident and on what the storage costs, and both belong to the team that runs the backend.

A period is paid for in bytes, so the [tail-rule example](#tail-sampling) that prints the kept share also measures what a message's trace takes. On baseline day 1 a message's span rows take 2,831 bytes in the JSON-lines export, with capture off, and the count holds span rows only. The kept traces of the incident day hold 42.6% of that day's bytes, against 42.0% of its spans. Here the bytes follow the spans closely, so the kept share of spans is a fair guide to the kept share of bytes on this day.

The count leaves content out. Capture is off until chapter 12, which turns it on for one named purpose and measures what prompts and replies add to this same export path. That byte count is therefore a lower bound for a message's trace. Sampling also decides only which spans reach the backend. It does not settle what the process does with the spans it drops, and chapter 12 shows what the upload hook does with content in those spans.

**Working rule:** Measure bytes per message on your own export, without content and then with any content you plan to keep, before you set a period. Keep the period beside the bytes it multiplies, and name what the bytes leave out.

## Where sampling goes wrong in production {#choose-what-to-keep-in-production}

A head ratio does what its share says and nothing more. It keeps the same expected share on a quiet day and on a day with a new failure, because its decision never reads a message. The kept set of the [tail rule](#tail-sampling) moves with the failures, which is why this chapter uses both. A head sample still has a use. It keeps a sample of ordinary traces, so the typical message can be read, and its decision needs no look at the message.

The two thresholds of the [tail rule](#tail-sampling) come from other parts of the book, and they move. The latency line is chapter 9's objective. The expensive line is the baseline day's 99th percentile of cost, which a release that changes cost moves with it. The expensive line is therefore read again after each release that changes what a message costs, and not kept from the first baseline.

The rule needs whole traces, and it judges the trace it has. A [detached root](#lost-context) starts a trace of its own, and the rule judges that trace by what it holds. On the incident day the example counts 4 such traces, each an MCP `notifications/cancelled` span sent after a timed-out lookup with no context current, and each judged alone. The rest of its message sits in another trace, which the rule may keep or drop on other grounds. The check covers the shape of the book's traces alone, and production may hold other shapes that it does not show.

**Working rule:** Judge a rule by what it keeps on the days that went wrong, not on a quiet day, and read each threshold again after a release that changes what it measures.

## The decisions this chapter made {#choose-what-to-keep-decisions}

The decisions below follow from one fact the examples show: a sampler's share is set before the message is known, so keeping the messages an engineer needs takes a rule that reads each whole trace.

- We keep the head ratio and the tail rule together. The head sample alone kept 2 of the 17 messages with an error, and the tail rule keeps all of them.
- The tail rule keeps errors first, then slow messages, then costly ones, under a budget of 120 spans. The budget sits above the spans the errors take, and one below them would drop an error.
- Every service samples with parent-based sampling, and only the root's service makes the decision. The contacts server follows the assistant's flag and runs no ratio of its own.
- [Chapter 6's rule for totals](#tokens-and-cost-decisions) holds here. A sampled estimate, printed with its interval, is for a split the counters cannot make, and it is only as good as each part's kept count.
- The retention period belongs to the team. We measure the bytes per message first, without content, and chapter 12 adds what content costs.

Two of these are judgements that the examples cannot settle. The budget of 120 spans is one, because it is the book's number and not a measured limit. Parent-based sampling is the other. The probe checks the SDK's default sampler on one server, and it says nothing about services that this book does not run. A reader who copies the rule should measure their own day first: the spans their errors take, the bytes per message, and the messages that are costly but neither erroneous nor slow. Only then should any number in this chapter become a setting.

What the chapter learned is narrower than a rule about sampling. A head sampler's share is fixed by the trace ID before the message runs, so only a rule that reads each whole trace keeps the messages an engineer needs. A total from the kept traces is an estimate, and it carries its interval wherever it is printed.

**Working rule:** Before you copy a sampling setting, run its example on a day you have recorded yourself, and keep each setting with the example that tests it.

# Keep private data out of telemetry

By the end of this chapter you can keep personal data out of the assistant's telemetry by default, turn content capture on for a stated purpose and count what that leaks, and say which leaks redaction can remove and which it cannot reach. You'll also run the scan that counts what is left, and you'll see which counts are zero by assertion and which are only measured.

Ambrewick's traces are read by people who did not write the assistant. The on-call engineer opens a trace after an alert, and the contacts team opens the traces that its own lookups joined. Some of what those traces hold is personal. Every message's root span carries the user's ID whether or not anyone asked for content, and the engineer who chases one wrong route will want the prompt and the reply. Capturing those puts the user's name in the same spans, next to the people, places and relations that the requests mention. The contacts server adds a leak that no capture switch controls. The problem, in the case, is that the trace that explains a wrong route is also a copy of the conversation.

The users, the tools and the contacts are synthetic, and the requests are MASSIVE's. The users' names come from fixed lists, their addresses sit on the `.example` domain, and the case has no payment or phone numbers of its own. The requests keep the person, place and relation values that MASSIVE annotates. Those values are request text that the dataset's crowd workers wrote, and this book leaves them as written, labelled by their slots. The scanner reads each span's values and its captured text, counts each kind it looks for, one item for each match, and this chapter reports the count that redaction cannot remove. Most of the examples replay baseline day 1. Where the contacts server matters, they read the incident day from [chapter 9](#an-alert-that-stays-quiet).

## Capture off comes first {#capture-off-by-default}

The [content capture](#the-capture-switch) switch from chapter 3 is the primary defence in this chapter, and it comes first. With the switch unset the package records no prompt and no reply, so there is nothing for a later step to remove. Everything after this section is for the cases where someone has turned the switch on. A service that has not named a purpose for content keeps the switch at its default, and it reads the default of every package it loads, because one package's default is not another's.

One model call under each of the four modes shows what each mode writes, to the span and to the logs.

Example `capture-modes` (Python 3.13.16 · bm25s 0.3.16 · httpx 0.28.1 · mcp 2.3.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""The four content modes of the official package, each set before the package is instrumented and run on the same
recorded answer call. The point rests on the printed pairs: only the span modes put the messages on the span, and only
the event modes write a log record, so SPAN_AND_EVENT writes both. The example prints counts, never the messages."""
import lib  # lib first: threads and seeds are fixed before anything else

import os

from opentelemetry.instrumentation.genai.openai import OpenAIInstrumentor
from opentelemetry.sdk._logs import LoggerProvider
from opentelemetry.sdk._logs.export import InMemoryLogRecordExporter, SimpleLogRecordProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

from lib.assistant import RELEASES
from lib.clock import VirtualClock
from lib.ids import SequentialIds
from lib.scan import CAPTURE, CONTENT_KEYS, captured_call, model_calls
from lib.tracing import make_provider

CALL = next(call for call in model_calls("baseline-day-1") if call["step"] == "answer")  # the day's first answer call
EXPECTED = {"NO_CONTENT": (0, 0), "SPAN_ONLY": (2, 0), "EVENT_ONLY": (0, 1), "SPAN_AND_EVENT": (2, 1)}


def run(mode: str) -> tuple[int, int, str]:
    """One call under `mode`: the content attributes on its span, the log records written, and the log's event name."""
    os.environ[CAPTURE] = mode  # the package reads the mode when it is instrumented, so it is set first
    spans, logs = InMemorySpanExporter(), InMemoryLogRecordExporter()
    logger_provider = LoggerProvider()
    logger_provider.add_log_record_processor(SimpleLogRecordProcessor(logs))  # where the event modes write their record
    provider = make_provider("ambrewick-assistant", RELEASES["r0"].service_version, "modes",
                             VirtualClock("2026-12-08"), SequentialIds(), spans,
                             "https://opentelemetry.io/schemas/1.45.0")
    instrumentor = OpenAIInstrumentor()
    instrumentor.instrument(tracer_provider=provider, logger_provider=logger_provider)
    captured_call(CALL)
    instrumentor.uninstrument()
    del os.environ[CAPTURE]
    content = sum(key.startswith(CONTENT_KEYS) for key in spans.get_finished_spans()[0].attributes)
    names = {record.log_record.event_name for record in logs.get_finished_logs()}
    return content, len(logs.get_finished_logs()), ", ".join(sorted(names))


for mode in EXPECTED:
    content, records, event = run(mode)
    print(f"content attributes on the span, {mode}: {content}")
    print(f"log records, {mode}: {records}")
    if event:
        print(f"event name on the log record, {mode}: {event}")
    assert (content, records) == EXPECTED[mode]  # the pairs the prose quotes
```

Output:

```text
content attributes on the span, NO_CONTENT: 0
log records, NO_CONTENT: 0
content attributes on the span, SPAN_ONLY: 2
log records, SPAN_ONLY: 0
content attributes on the span, EVENT_ONLY: 0
log records, EVENT_ONLY: 1
event name on the log record, EVENT_ONLY: gen_ai.client.inference.operation.details
content attributes on the span, SPAN_AND_EVENT: 2
log records, SPAN_AND_EVENT: 1
event name on the log record, SPAN_AND_EVENT: gen_ai.client.inference.operation.details
```

With the switch unset, the content is in neither place: the span holds 0 content attributes, and the package writes 0 log records. The span modes put the prompt and the reply on the span, and the event modes write a log record, as the next section describes. That pair is the whole case for the primary defence: the content is not in the telemetry, so nothing downstream can leak it.

Capture off does not mean that nothing leaves. The user's ID sits on every message's root span whichever mode is set, and the [leak example](#what-leaks-when-capture-is-on) asserts one such span for each message, whatever the capture setting. The ID is the user's own identifier, and a trace needs some identifier to answer which user a message came from, so it cannot be left out. It has to be replaced before it is stored, and [keyed user pseudonyms](#keyed-user-pseudonyms) show how.

No email address appears in any span of baseline day 1, with capture on or off. The assistant's policy tells the model never to repeat a contact's address in a reply, and no tool span carries its arguments, so an address has no route into a span. The scanner finds no address before [redaction](#redaction-as-defence-in-depth) or after it. The email kind reads zero because the design gives an address no route, and the scanner, which looks for every case address as written, confirms it.

Names behave differently. With capture off, the [leak example](#what-leaks-when-capture-is-on) asserts that no user name and no message text reaches a span. Names appear only when capture is on, which the next section measures.

**Working rule:** Keep content capture off in every service, and read the default of each loaded package before you deploy it. Turn capture on only for a purpose you can name, and only where a redactor runs on every span before the backend keeps it.

## What leaks when capture is on {#what-leaks-when-capture-is-on}

Suppose an engineer turns capture on to debug one wrong route. The reason is a good one, and what it costs is the same for every message that day. Each mode writes content to a different place. In `SPAN_ONLY` the prompt and the reply go into two span attributes, `gen_ai.input.messages` and `gen_ai.output.messages`, the names the registry gives them. The system text is folded into the input messages, so the instructions the model was given travel with the user's text. In `EVENT_ONLY` the same content goes onto a log record named `gen_ai.client.inference.operation.details`, and the span holds none of it. `SPAN_AND_EVENT` writes both. The logs SDK is still published under the private `opentelemetry.sdk._logs` at 1.45.2. A reader configures a `LoggerProvider` from it, and `InMemoryLogRecordExporter` is the class that reads records back. The package writes through the logs API, not that path. A second switch writes content as well. The upload hook writes messages to a store whenever it is on, with capture set or not, and [keeping content by reference](#keep-content-by-reference) shows what that does.

A personal-looking value is a person, place or relation name in a request's text, written by the dataset's crowd workers and labelled by its slots; it looks like personal data in a span and is treated as such; it was written for the dataset and is not drawn from anyone's messages, though the dataset keeps some public names as written. [Data Governance as Code](https://rollingedition.com/concepts/data-governance/personal-data) treats personal data as data that relates to an identifiable person. The handling here, to find, redact and count, is the same. The same reading covers the other slot labels the scanner counts. The scanner finds these values by their words in the captured text. A word that is a value under one label can match under another, so the counts are measures.

Running the day twice, with capture off and then on, shows what each run's spans hold.

Example `leak-with-capture-on` (Python 3.13.16 · bm25s 0.3.16 · httpx 0.28.1 · mcp 2.3.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""What the day's telemetry holds before any redaction, with content capture off and on, and the stack traces that leave the
contacts server with capture off. The point rests on the printed counts: every root span holds its user's ID either way,
the names and the dataset's values appear only with capture on, and the server's error spans carry stack traces that
reach the receiver. The example prints counts and the shape of one path, never a value or a full path."""
import lib  # lib first: threads and seeds are fixed before anything else

import re
from pathlib import Path

from lib.case import load_messages
from lib.dayrun import run_day_traced
from lib.report import fmt_int
from lib.scan import KINDS, captured_day, label, live_rows, of_service, scan_rows, spans_holding, stack_traces

DAY, INCIDENT = "2026-12-08", "2026-12-09"   # baseline day 1, and the incident day, whose contacts server fails
assistant = run_day_traced(DAY, live=False).spans  # the assistant's own spans; the replay keeps no content
content = captured_day(DAY)                        # the day's model calls through the package, content on
rows = assistant + content
items, spans = scan_rows(rows), spans_holding(rows)
print("messages on the day:", fmt_int(len(load_messages(DAY))))
print("spans, capture off:", fmt_int(len(assistant)))
print("spans from the package, capture on:", fmt_int(len(content)))
for kind in KINDS:
    if kind != "stacktrace":  # the stack traces are on the incident day, below
        print(f"{label(kind)} items, capture off and on: {fmt_int(items[kind])}")
        print(f"{label(kind)} spans holding it: {fmt_int(spans[kind])}")
off = scan_rows(assistant)
assert all(off[kind] == 0 for kind in KINDS if kind not in ("user_id", "stacktrace"))  # capture off: no name, no text
assert spans["user_id"] == len(load_messages(DAY))  # one root span per message, each with the user's ID, whatever the capture
assert items["user_name"] > 0 and items["slot:person"] > 0  # capture on: names and the dataset's values reach spans

# The incident day through the book's receiver, capture off. The contacts server's error spans carry the traceback.
live = live_rows(INCIDENT)
server, mine = of_service(live, "contacts-server"), of_service(live, "ambrewick-assistant")
server_traces = stack_traces(server)
errors = sum(row["status"] == "ERROR" for row in server if row["name"] == "contacts.lookup")
traced = {row["trace_id"] for row in live if stack_traces([row])}
print("contacts server spans the receiver stored:", fmt_int(len(server)))
print("contacts.lookup spans in error:", fmt_int(errors))
print("stack traces on the contacts server's spans:", fmt_int(len(server_traces)))
print("stack traces on the assistant's spans:", fmt_int(len(stack_traces(mine))))
print("incident traces holding a stack trace:", fmt_int(len(traced)))
print("file paths named in the server's stack traces:", fmt_int(sum(t.count('File "') for t in server_traces)))
# The innermost frame names the file and line that raised. Only the file's name is printed; its folder is a placeholder.
path, line, function = re.findall(r'File "([^"]+)", line (\d+), in (\S+)', server_traces[0])[-1]
print(f'innermost frame, first server trace: File "<folder>/{Path(path).name}", line {line}, in {function}')
assert len(server_traces) == errors and stack_traces(mine)  # every error span of the server carries its traceback
```

Output:

```text
messages on the day: 200
spans, capture off: 675
spans from the package, capture on: 321
user_id items, capture off and on: 200
user_id spans holding it: 200
user_name items, capture off and on: 2
user_name spans holding it: 2
email items, capture off and on: 0
email spans holding it: 0
person slot items, capture off and on: 55
person slot spans holding it: 38
place_name slot items, capture off and on: 44
place_name slot spans holding it: 33
relation slot items, capture off and on: 26
relation slot spans holding it: 25
email_address slot items, capture off and on: 0
email_address slot spans holding it: 0
personal_info slot items, capture off and on: 0
personal_info slot spans holding it: 0
contacts server spans the receiver stored: 22
contacts.lookup spans in error: 3
stack traces on the contacts server's spans: 3
stack traces on the assistant's spans: 4
incident traces holding a stack trace: 5
file paths named in the server's stack traces: 9
innermost frame, first server trace: File "<folder>/contacts_server.py", line 164, in find_contact
```

With capture off, each of the 200 messages leaves a user ID on its root span, and no name or message text reaches a span. With capture on, names reach 2 spans and the spans holding a person value number 38. The text sits in the package's model-call spans, of which there are 321, while the assistant's own spans carry no text. The next section's redaction is the answer to what the text leaves behind.

Capture also adds bytes to every message's trace, and [chapter 11](#retention) asked for that number before any period was set. Measuring the bytes on the same export path puts a number on the cost.

Example `content-bytes-per-message` (Python 3.13.16 · bm25s 0.3.16 · httpx 0.28.1 · mcp 2.3.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""What content capture adds to a message's bytes on baseline day 1, and what the SDK does to a long content value. A
message's bytes are those of its spans' rows in the JSON-lines export. The assistant's own spans carry no content, so the
bytes content adds are the difference between the package's spans for the same calls with capture on and off. The point
rests on the printed bytes per message and on the value limit's count of cut values, which the example also checks."""
import lib  # lib first: threads and seeds are fixed before anything else

import os

from lib.case import load_messages
from lib.dayrun import run_day_traced
from lib.report import fmt_int, fmt_share
from lib.sampling import row_bytes
from lib.scan import CONTENT_KEYS, captured_day, is_json

DAY = "2026-12-08"
LIMIT = 1000  # characters, for the value limit below
messages = len(load_messages(DAY))
assistant = run_day_traced(DAY, live=False).spans  # the message's spans, capture off: no content in them
off, on = captured_day(DAY, "NO_CONTENT"), captured_day(DAY, "SPAN_ONLY")
added = row_bytes(on) - row_bytes(off)  # the bytes content adds to the package's spans, over every call of the day
total = row_bytes(assistant) + added
print("bytes per message, capture off:", fmt_int(round(row_bytes(assistant) / messages)))
print("bytes content adds per message, capture on:", fmt_int(round(added / messages)))
print("bytes per message, capture on:", fmt_int(round(total / messages)))
print("content share of the bytes, capture on:", fmt_share(added, total))


values = [value for row in on for key, value in row["attributes"].items() if key.startswith(CONTENT_KEYS)]
os.environ["OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT"] = str(LIMIT)  # read when the provider is made: set before captured_day
cut = [value for row in captured_day(DAY) for key, value in row["attributes"].items() if key.startswith(CONTENT_KEYS)]
del os.environ["OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT"]
pairs = [(full, short) for full, short in zip(values, cut) if len(full) > LIMIT]  # each value, with and without limit
print("longest content value, no limit:", fmt_int(max(map(len, values))), "characters")
print(f"value length limit: {LIMIT:,} characters")
print("longest content value, cut at the limit:", fmt_int(max(map(len, cut))), "characters")
print("content values on the day:", fmt_int(len(values)))
print("content values cut by the limit:", fmt_int(len(pairs)))
print("cut values that no longer parse as JSON:", fmt_int(sum(not is_json(short) for _, short in pairs)))
# Nothing in the span marks a cut value, so a reader sees a shorter, broken message and no flag.
assert len(cut) == len(values) and max(map(len, cut)) == LIMIT
assert all(len(short) == LIMIT for _, short in pairs)
assert all(not is_json(short) for _, short in pairs)  # a value cut at a character is no longer JSON
```

Output:

```text
bytes per message, capture off: 2,831
bytes content adds per message, capture on: 2,716
bytes per message, capture on: 5,547
content share of the bytes, capture on: 49.0%
longest content value, no limit: 2,907 characters
value length limit: 1,000 characters
longest content value, cut at the limit: 1,000 characters
content values on the day: 642
content values cut by the limit: 87
cut values that no longer parse as JSON: 87
```

Content nearly doubles a message's bytes. With capture off, a message's span rows take 2,831 bytes, the figure chapter 11 printed. With capture on they take 5,547, so content adds 2,716 bytes, which is 49.0% of the total. The bytes are those of each span's row in the JSON-lines export.

The SDK can also cut a long value. The longest content value on the day is 2,907 characters long. Under a value length limit of 1,000 characters, that value is cut to the limit. The limit touches 87 of the 642 values, and every cut value fails to parse as JSON. A value cut at a character is shorter, and it no longer reads as the structure it was. The limit counts characters, not bytes, so a value cut at the limit can still take more bytes than the limit suggests.

**Working rule:** Measure a message's bytes with content on, as well as with it off, before you choose a retention period. Count the bytes against the export the period will keep, and do not assume that a limit leaves a readable value.

## Stack traces leak without capture {#stack-traces-leak-without-capture}

The contacts server is a separate process, and its spans reach the receiver by a route the assistant's code does not control. [Chapter 4](#the-contacts-server) introduced the server, and [chapter 5](#the-book-receiver) showed that it exports its own spans over OTLP when it is given an endpoint. The server opens its `contacts.lookup` span with `start_as_current_span` and sets nothing about exceptions, so the API's default, `record_exception=True` at 1.45.2, writes an `exception` event on that span when a tool raises. The event can carry `exception.stacktrace`, the traceback. A traceback names each file by its path, and those paths name the folders of the process that ran the code.

Capture was off when the [leak example](#what-leaks-when-capture-is-on) read the incident day, and the stack traces were there anyway. On that day the receiver stored 22 contacts server spans. 3 of its `contacts.lookup` spans were in error, and each of those error spans carried a stack trace, 3 in all. Between them the traces name 9 file paths. The innermost frame of the first one is `find_contact`, in the server's own file, `contacts_server.py`, under a placeholder for the folder. The output prints the shape of that path and never the path itself, since a full path is what this section is about. The fix below drops only `exception.stacktrace`: the exception event, with its class and message, stays, as [chapter 8 decided](#find-the-failure-decisions).

The assistant's own spans carry stack traces as well, 4 of them on the incident day. The MCP SDK's client dispatcher writes those on the client spans, and the tool-attempt spans carry only the exception's class and message. So the traceback leaves from both processes, and the leak does not depend on what the assistant chooses to record. Tail sampling in [chapter 11](#tail-sampling) keeps a trace whose message has an error, and the scan reads every one of the 5 traces that hold a stack trace, kept or dropped.

A stack trace names no user, but its paths can name the account that ran the process, which is personal data, and they reveal the machine. The scanner counts stack traces as a kind of their own, apart from the personal items. A reader might ask whether the traceback is worth keeping. The engineer who opens a trace needs the exception's class and message, which the span keeps, and the failing tool's name, which it also keeps. The folder names add nothing a fix needs.

This is the leak that capture cannot stop, and the assistant's redactor cannot reach the server's half of it. The [redaction section](#redaction-as-defence-in-depth) counts what is left after the assistant's redactor runs, and shows where a redactor does reach these traces.

**Working rule:** Treat a stack trace as sensitive in every service, and keep it out of any backend. Remove it where every service's spans pass. At the source, ask the team that owns the server to set `record_exception=False` on the span and to set the exception's class and message by hand, since the client's traces can only be removed downstream.

## Redaction is defence in depth {#redaction-as-defence-in-depth}

Redaction replaces a personal value in a span's attributes or events with a placeholder before the span is stored: in the process that made it, or where every service's spans pass. The assistant's process does that with a span processor, as [chapter 1](#spans-by-hand) defined it. This processor exports a redacted copy of each span as the span ends. It has to copy, because the SDK freezes a span's attributes when the span ends, and after that an in-place edit is not possible. [Data Governance as Code's `redact`](https://rollingedition.com/concepts/data-governance/redact) is a NULL cast on a query's column, which is a different operation from this one, since this redaction applies to telemetry.

What the processor removes is specific. The synthetic users' names and addresses become the placeholders `[name]` and `[email]`. A user ID becomes its pseudonym, which the next section defines. A stack trace is dropped rather than replaced, because its paths name the folders of the process that ran the code. A `file://` reference keeps its scheme and its file name, and its folder becomes a placeholder. A span's status description is redacted too, since it can hold an exception's message. Personal-looking values pass through unchanged, since the processor cannot tell a name in free text from any other word, and the case gives it no labels that would tell them apart.

The next example runs the processor over the day's spans and counts what it leaves, then runs the receiver's redaction over the incident day's stored rows.

Example `scan-after-redaction` (Python 3.13.16 · bm25s 0.3.16 · httpx 0.28.1 · mcp 2.3.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""The scanner's count after redaction, with the redacting processor on every set of spans. On baseline day 1 the synthetic
kinds are asserted zero, and MASSIVE's slot labels are counted before and after, their residue printed and never asserted
zero. On the incident day the contacts server's stack traces reach the receiver, and the receiver's redaction removes them
from both processes' spans. The point rests on the zeros and on the residue; the example prints counts only."""
import lib  # lib first: threads and seeds are fixed before anything else

from lib.redact import redact_row
from lib.report import fmt_int
from lib.scan import SLOT_LABELS, SYNTHETIC, absolute_paths, assistant_rows, captured_day, label, live_rows, of_service
from lib.scan import scan_rows, stack_traces

DAY, INCIDENT = "2026-12-08", "2026-12-09"
before = scan_rows(assistant_rows(DAY) + captured_day(DAY))  # the day's spans, as they are made
after = scan_rows(assistant_rows(DAY, redact=True) + captured_day(DAY, redact=True))  # the same, through the processor
for kind in SYNTHETIC:
    print(f"{kind} items before redaction: {fmt_int(before[kind])}")
    print(f"{kind} items after redaction: {fmt_int(after[kind])}")
SLOTS = [f"slot:{name}" for name in SLOT_LABELS]
for kind in SLOTS:  # counted in the captured text: measured, not asserted zero
    print(f"{label(kind)}, items before redaction: {fmt_int(before[kind])}")
    print(f"{label(kind)}, residue after redaction: {fmt_int(after[kind])}")
assert all(after[kind] == 0 for kind in SYNTHETIC)  # the synthetic users' items are all removed
assert all(after[kind] == before[kind] for kind in SLOTS)  # values untouched

# The incident day's rows as the receiver stores them: the assistant's spans and the contacts server's spans.
live = live_rows(INCIDENT)
cleaned = [redact_row(row) for row in live]  # the receiver's redaction, over both processes' spans
OWN, SERVER = "ambrewick-assistant", "contacts-server"
print("stack traces on the assistant's spans, before redaction:", fmt_int(len(stack_traces(of_service(live, OWN)))))
print("stack traces on the contacts server's spans, before redaction:",
      fmt_int(len(stack_traces(of_service(live, SERVER)))))
print("stack traces on the assistant's spans, after redaction at the receiver:",
      fmt_int(len(stack_traces(of_service(cleaned, OWN)))))
print("stack traces on the contacts server's spans, after redaction at the receiver:",
      fmt_int(len(stack_traces(of_service(cleaned, SERVER)))))
assert not stack_traces(cleaned)  # the receiver's redaction reaches both processes' spans
assert stack_traces(of_service(live, SERVER))  # the server's spans reach the receiver with their traces
assert absolute_paths(cleaned) == 0 and absolute_paths(live) > 0  # no path survives redaction; the raw rows hold paths
```

Output:

```text
user_id items before redaction: 200
user_id items after redaction: 0
user_name items before redaction: 2
user_name items after redaction: 0
email items before redaction: 0
email items after redaction: 0
person slot, items before redaction: 55
person slot, residue after redaction: 55
place_name slot, items before redaction: 44
place_name slot, residue after redaction: 44
relation slot, items before redaction: 26
relation slot, residue after redaction: 26
email_address slot, items before redaction: 0
email_address slot, residue after redaction: 0
personal_info slot, items before redaction: 0
personal_info slot, residue after redaction: 0
stack traces on the assistant's spans, before redaction: 4
stack traces on the contacts server's spans, before redaction: 3
stack traces on the assistant's spans, after redaction at the receiver: 0
stack traces on the contacts server's spans, after redaction at the receiver: 0
```

Redaction removes every synthetic item the day holds and leaves the personal-looking values as they were, and the example asserts both. The 200 user IDs and the 2 user names fall to zero. The email kind has no items before or after, for the reason the [first section](#capture-off-by-default) gives. The 55 person values are all still there after redaction: the residue is 55, and the other slot labels are printed beside it.

On the incident day the stack traces reach the receiver from both processes, and redaction there removes them. The assistant's spans hold 4 stack traces and the contacts server's spans hold 3. The server's spans go from its exporter to the receiver without passing the assistant's processor, so that processor cannot see them. After redaction at the receiver, the counts are 0 and 0.

The receiver is where both processes' spans pass. [Chapter 5](#the-book-receiver) stored them there, and the example runs the same redaction over the stored rows. That is the second place the definition names, where every service's spans pass, and [changing the backend](#changing-backends) in chapter 5 named the Collector as the place where a rule sees every service's spans. The Collector's redaction processor does this work in production. It deletes keys that are not on an allow-list and masks values that match a blocked list, and its README calls it "one line of defence rather than the only compliance measure in place". The receiver stands in for that place in this book.

A process can redact only the spans it writes, so a redactor in one service protects that service and nothing else. Redaction works where the spans of every service pass, and a redactor in each process is a second line behind that.

**Working rule:** Run redaction in every process, so that it covers what that process writes, and run it again where every service's spans pass, so that it covers what the other processes write. Count the items after both. A non-zero count of a synthetic kind is a failure, and a non-zero count of a personal-looking value is the redactor's reach.

## Keyed user pseudonyms {#keyed-user-pseudonyms}

A user ID is the one identifier that every trace keeps, so redaction has to replace it and not drop it. A keyed pseudonym replaces a user ID with an HMAC-SHA256 of it under a key, kept to twelve hexadecimal digits, the same for one user wherever it appears. [Data Governance as Code](https://rollingedition.com/concepts/data-governance/keyed-pseudonym) has a keyed pseudonym of its own, which is related to this one and is not the same. That book keeps eight digits and hashes the entity type and the case-folded value under a key only its corpus job holds. This chapter's code keeps twelve digits and hashes the raw user ID under a demonstration key in the code, because the case has one identifier type and the key is there to show the construction.

The key matters because the user IDs are sequential, so anyone can write out every candidate. A plain SHA-256 of each candidate matches a stored hash directly, and the hash of a real ID protects nothing. The key changes the question. A reader who does not hold the key can hash every candidate and still match nothing.

Trying every candidate ID against one stored hash shows what the key is for.

Example `redact-and-hash` (Python 3.13.16 · bm25s 0.3.16 · httpx 0.28.1 · mcp 2.3.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""The redacting processor, and the keyed pseudonym that replaces a user ID. Redaction is defence in depth: it removes
what the process can recognise from each span before the span is exported. The point rests on two printed results: the
processor's spans hold no synthetic name or address, and a keyed hash resists the enumeration that an unkeyed hash of
the same candidate IDs does not. The demonstration key is in the code, so the last enumeration succeeds, as it must."""
import lib  # lib first: threads and seeds are fixed before anything else

import hashlib
import hmac

from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

from lib.case import load_users
from lib.ids import SequentialIds
from lib.redact import USER_ID_ATTRIBUTE, RedactingProcessor, hash_user, pseudonym
from lib.report import fmt_int
from lib.scan import SYNTHETIC, captured_day, scan_rows

DAY = "2026-12-08"
raw, redacted = captured_day(DAY), captured_day(DAY, redact=True)  # the same calls, without and with the processor
before, after = scan_rows(raw), scan_rows(redacted)
for kind in SYNTHETIC:
    print(f"{kind} before the processor: {fmt_int(before[kind])}")
    print(f"{kind} after the processor: {fmt_int(after[kind])}")
assert all(after[kind] == 0 for kind in SYNTHETIC)  # the processor removes every synthetic item the day's calls hold

# A root span with a user ID goes through the same processor. The attribute the span exports is the pseudonym.
TARGET = load_users()[0].user_id  # one of the case's synthetic users; not printed
exporter = InMemorySpanExporter()
provider = TracerProvider(id_generator=SequentialIds())
provider.add_span_processor(RedactingProcessor(exporter))  # the only path to the exporter
provider.get_tracer("ambrewick.assistant").start_span("invoke_agent ambrewick-assistant",
                                                      attributes={USER_ID_ATTRIBUTE: TARGET}).end()
root = exporter.get_finished_spans()[0]
print("user ID on the root span, after the processor:", root.attributes[USER_ID_ATTRIBUTE])
assert root.attributes[USER_ID_ATTRIBUTE] == pseudonym(TARGET) and TARGET not in str(dict(root.attributes))

# An attacker holds one stored hash of a user ID and tries every ID the format allows: U0000 to U9999.
CANDIDATES = [f"U{number:04d}" for number in range(10_000)]
stored_plain = hashlib.sha256(TARGET.encode("utf-8")).hexdigest()  # an unkeyed SHA-256 of the ID
stored_keyed = hash_user(TARGET)                                    # the keyed pseudonym, as the redactor makes it
print("candidate IDs tried:", fmt_int(len(CANDIDATES)))
found_plain = sum(hashlib.sha256(c.encode("utf-8")).hexdigest() == stored_plain for c in CANDIDATES)
print("unkeyed SHA-256 matches for the stored hash:", fmt_int(found_plain))
guess = b"a key the attacker does not hold"
found_guess = sum(hmac.new(guess, c.encode("utf-8"), hashlib.sha256).hexdigest() == stored_keyed for c in CANDIDATES)
print("keyed HMAC matches, with a key the attacker does not hold:", fmt_int(found_guess))
found_demo = sum(hash_user(c) == stored_keyed for c in CANDIDATES)  # with DEMO_KEY, which is in lib/redact.py
print("keyed HMAC matches, with the demonstration key in the code:", fmt_int(found_demo))
assert (found_plain, found_guess, found_demo) == (1, 0, 1)  # the key is the protection, and the code shows the one here
```

Output:

```text
user_id before the processor: 0
user_id after the processor: 0
user_name before the processor: 2
user_name after the processor: 0
email before the processor: 0
email after the processor: 0
user ID on the root span, after the processor: user-fd52e7ae5e26
candidate IDs tried: 10,000
unkeyed SHA-256 matches for the stored hash: 1
keyed HMAC matches, with a key the attacker does not hold: 0
keyed HMAC matches, with the demonstration key in the code: 1
```

A keyed hash resists the enumeration that an unkeyed one does not. Of the 10,000 candidate IDs tried against one stored hash, an unkeyed SHA-256 finds 1 match, which is the target, while a keyed HMAC with a key the attacker does not hold finds 0. The same keyed HMAC with the demonstration key, which is written in this book's code, finds 1 match.

The last count is why the key has to be secret in practice. The demonstration key in the code is not a secret, since anyone who reads the file holds it. The run shows the construction and does not protect an identifier. We recommend a secret store for a real key, kept away from the code and from the telemetry.

That is why a pseudonym is safer than the raw ID to put in a span, which [chapter 4](#what-goes-in-baggage) promised to explain. It is not anonymous, though. A stable pseudonym still links all of one user's spans, so an engineer can find every message from the same user, and the content beside it can still identify the user. [OpenTelemetry's guidance on handling sensitive data](https://opentelemetry.io/docs/security/handling-sensitive-data/) notes that hashing may not give the anonymity a team needs. A user ID does not go into baggage, and the pseudonym does not go there either. In a span the pseudonym names no one to a reader who lacks the key, and the redactor applies the same pseudonym to a user ID that appears in a message's text, so two spans about one user still match after redaction.

**Working rule:** Key every pseudonym with a secret that the telemetry's readers never hold, and keep the key outside the code. Change the key only with a plan, since a new key starts every user's pseudonym again, and the traces made before the change no longer join the ones made after it.

## Keep content by reference {#keep-content-by-reference}

Redaction removes what it knows how to find. Another route keeps the content out of the span altogether. An external content reference puts a pointer in the span, a `*_ref` attribute, and the content itself in a store with its own access rules.

The package has an upload hook, which the variable `OTEL_INSTRUMENTATION_GENAI_COMPLETION_HOOK` names, with the value `upload`. The specification names the variable `OTEL_INSTRUMENTATION_GENAI_CONTENT_HOOK`, but the package reads only the completion-hook name, so that is the one to set. The hook writes each call's messages to files and puts references on the span, `gen_ai.input.messages_ref` and `gen_ai.output.messages_ref`, which are the registry's names. The hook also needs `OTEL_INSTRUMENTATION_GENAI_UPLOAD_BASE_PATH` set, and it imports `fsspec`, which this book pins at 2026.9.0. [Chapter 3](#the-capture-switch) set neither, so this is the first point in the book where the hook runs.

Sending the same twenty calls through the hook three ways sorts out where the content goes.

Example `content-by-reference` (Python 3.13.16 · bm25s 0.3.16 · httpx 0.28.1 · mcp 2.3.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""The upload hook, which writes each call's messages to a store and puts a reference on the span. The same twenty calls
run three ways: capture unset with the span sampled in, capture on, and the span sampled out. The point rests on the
printed counts: with capture unset the span holds only references while the store holds the user's text, and with the
span sampled out nothing is exported and the store still fills. References are printed after the redactor has replaced
their folder. The store is a folder this example makes and removes."""
import lib  # lib first: threads and seeds are fixed before anything else

import re
import tempfile
from pathlib import Path

from opentelemetry.sdk.trace.sampling import ALWAYS_OFF, ALWAYS_ON

from lib.dayrun import RECORDINGS
from lib.redact import has_absolute_path, redact_text
from lib.report import fmt_int
from lib.scan import CONTENT_KEYS, hooked_calls, model_calls, print_hook_run

CALLS = model_calls(RECORDINGS["2026-12-08"])[:20]  # twenty of baseline day 1's model calls
USER_TEXTS = [next(m["content"] for m in reversed(c["request"]["messages"]) if m["role"] == "user") for c in CALLS]
UUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")  # the uploaded files' random names

with tempfile.TemporaryDirectory() as root:
    unset_spans, unset = hooked_calls(CALLS, ALWAYS_ON, None, Path(root) / "unset")
    print_hook_run("capture unset and sampled in", unset_spans, unset)
    on_spans, on = hooked_calls(CALLS, ALWAYS_ON, "SPAN_ONLY", Path(root) / "on")
    print_hook_run("capture on and sampled in", on_spans, on)
    out_spans, out = hooked_calls(CALLS, ALWAYS_OFF, None, Path(root) / "out")
    print_hook_run("capture unset and sampled out", out_spans, out)
    refs = [s.attributes[k] for s in unset_spans for k in s.attributes if k.endswith("_ref")]
    redacted = [redact_text(ref) for ref in refs]  # the redactor replaces each reference's folder
    print("reference form on the span, after redaction:", UUID.sub("<id>", redacted[0]))
    print("absolute paths left in the redacted references:", fmt_int(sum(has_absolute_path(r) for r in redacted)))
    held = sum(any(text in body for body in unset["inputs"]) for text in USER_TEXTS)
    print("calls sent through the hook:", fmt_int(len(CALLS)))
    print("calls whose user text is in an uploaded input file, capture unset:", fmt_int(held))

assert len(unset_spans) == len(CALLS) and len(on_spans) == len(CALLS)  # every call's span is exported when sampled in
assert all(any(k.endswith("_ref") for k in s.attributes) for s in unset_spans)  # the span holds a reference
assert not any(k in CONTENT_KEYS for s in unset_spans for k in s.attributes)  # and no inline content, capture unset
assert all(any(k in CONTENT_KEYS for k in s.attributes) for s in on_spans)  # capture on: the content is inline
assert len(out_spans) == 0 and len(out["inputs"]) == len(CALLS) and len(out["outputs"]) == len(CALLS)  # sampled out
assert held == len(CALLS)  # the store holds each call's user text, with capture unset
assert all(has_absolute_path(ref) for ref in refs) and not any(has_absolute_path(r) for r in redacted)
```

Output:

```text
spans exported, capture unset and sampled in: 20
spans with a content reference, capture unset and sampled in: 20
spans with inline content, capture unset and sampled in: 0
uploaded inputs, capture unset and sampled in: 20
uploaded outputs, capture unset and sampled in: 20
spans exported, capture on and sampled in: 20
spans with a content reference, capture on and sampled in: 20
spans with inline content, capture on and sampled in: 20
uploaded inputs, capture on and sampled in: 20
uploaded outputs, capture on and sampled in: 20
spans exported, capture unset and sampled out: 0
spans with a content reference, capture unset and sampled out: 0
spans with inline content, capture unset and sampled out: 0
uploaded inputs, capture unset and sampled out: 20
uploaded outputs, capture unset and sampled out: 20
reference form on the span, after redaction: file://<folder>/<id>_inputs.json
absolute paths left in the redacted references: 0
calls sent through the hook: 20
calls whose user text is in an uploaded input file, capture unset: 20
```

With capture unset, the span holds a reference and no content, and the store holds the user's text: 20 input files, one for each call. Capture on adds the content inline to each of the 20 spans as well. Sampling the span out keeps it from the exporter altogether, and the hook still uploads each call's inputs and outputs: 20 inputs and 20 outputs, with no span exported.

The hook therefore writes for a span that the exporter never sends. [Chapter 11](#retention) said that sampling decides which spans reach the backend, and not what the process does with the spans it drops. The third run shows that point in practice. Content goes to the store even when the trace it belongs to is sampled out.

The reference is a `file://` address with the upload folder in it, which is an absolute path on the machine that wrote the file, so a reader who finds an unredacted reference learns where the file sits on that machine. The redactor replaces the folder with a placeholder and keeps the scheme and the file name. The example prints the reference after redaction, and the number of redacted references that still name a folder is 0.

The hook is not a privacy control. With capture unset, 20 of the 20 calls had their user text in an uploaded input file. Moving the content moved it. The redactor does not reach the files, so the store needs its own access rules and its own retention, and the same care as the spans the content came from.

**Working rule:** Do not turn on the upload hook as a way to keep content out of spans. Turn it on only with a store that has its own access and retention rules, and check the store as carefully as the spans, including the spans that sampling drops. Where spans pass, rewrite a reference's machine path, or use a store address that holds no machine path.

## Count what redaction leaves {#scanning-and-counting}

The scanner counts three groups of kinds, and this chapter keeps them apart in every table and figure. The first group is the synthetic users' items: user IDs, user names and email addresses, which redaction must remove. The second is the stack trace, which [an earlier section](#stack-traces-leak-without-capture) covered. The third is MASSIVE's slot labels, the person, place, relation and other values the scanner finds in the captured text. The first group is asserted zero after redaction. The third is measured.

The split follows what each group allows. The redactor knows the synthetic items, since they come from the case's own lists and the `.example` domain, so it can remove them, and the example asserts that it does. The zero means something because the scanner looks for the case's own values, not for the patterns the redactor matches. The redactor cannot know which words in a request are a person's name, because the app does not have the dataset's labels. Asserting zero for the slot labels would need those labels. So the example counts them before and after redaction, and the residue is 55 person values after redaction.

Two slot labels need a further word. The English annotations in the slice the book ships give `email_address` no values at all, so its pattern matches nothing and its zero follows from that slice. `personal_info` has one annotated phrase, and the scanner finds none of it in the day's captured text. That zero is a measurement, which is why it appears in the residue and not as an assertion.

The next example draws the spans that hold each kind, before and after redaction, in two panels.

Example `figure-personal-items-before-after` (Python 3.13.16 · bm25s 0.3.16 · httpx 0.28.1 · matplotlib 3.11.2 · mcp 2.3.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4), passing in Edition 2026.11.2:

```python
"""How many spans of baseline day 1 hold each kind of personal item, before and after redaction, in two panels: the
synthetic users' items, which redaction removes, and MASSIVE's personal-looking values, which it cannot tell apart from
other words and so leaves. The figure's point rests on the printed counts: the top panel's bars drop to zero, and the
bottom panel's stay where they were."""
import lib  # lib first: threads and seeds are fixed before anything else

from lib.figures import ACCENT, MUTED, RULE, new_figure, save
from lib.report import fmt_int
from lib.scan import SLOT_LABELS, SYNTHETIC, assistant_rows, captured_day, spans_holding

DAY = "2026-12-08"
rows = assistant_rows(DAY) + captured_day(DAY)  # the day's spans, capture on for the package's
cleaned = assistant_rows(DAY, redact=True) + captured_day(DAY, redact=True)  # the same, through the processor
before, after = spans_holding(rows), spans_holding(cleaned)
for kind in SYNTHETIC + tuple(f"slot:{label}" for label in SLOT_LABELS):
    label = kind.replace("slot:", "") + (" slot" if kind.startswith("slot:") else "")
    print(f"{label} spans before redaction: {fmt_int(before[kind])}")
    print(f"{label} spans after redaction: {fmt_int(after[kind])}")
assert all(after[kind] == 0 for kind in SYNTHETIC)  # the synthetic users' spans are all clean after redaction
assert all(after[f"slot:{label}"] == before[f"slot:{label}"] for label in SLOT_LABELS)  # measured, not moved

top_kinds = list(SYNTHETIC)
bottom_kinds = [f"slot:{label}" for label in SLOT_LABELS]
fig, (top, bottom) = new_figure(rows=2, height=5.6, sharex=False)  # one x scale per panel: 200 and 55 do not share one


def panel(ax, kinds, title):
    """Before and after, as horizontal bars, with each count printed at the bar's end."""
    ys = list(range(len(kinds)))
    xmax = max(before[kind] for kind in kinds) * 1.3 or 1  # room for the count and the legend
    ax.barh([y - 0.18 for y in ys], [before[kind] for kind in kinds], height=0.34, color=MUTED,
            label="before redaction")
    ax.barh([y + 0.18 for y in ys], [after[kind] for kind in kinds], height=0.34, color=RULE, edgecolor=ACCENT,
            hatch="////", label="after redaction")  # hatched, so the two bars differ by pattern as well as colour
    for y, kind in zip(ys, kinds):
        ax.text(before[kind] + xmax * 0.01, y - 0.18, str(before[kind]), va="center", fontsize=7.5)
        ax.text(after[kind] + xmax * 0.01, y + 0.18, str(after[kind]), va="center", fontsize=7.5)
    ax.set_yticks(ys, [kind.replace("slot:", "") for kind in kinds])
    ax.invert_yaxis()
    ax.set_xlim(0, xmax)
    ax.set_title(title, loc="left", fontsize=9)


panel(top, top_kinds, "Synthetic users' items: redaction removes them")
panel(bottom, bottom_kinds, "MASSIVE's personal-looking values: counted, not removed")
bottom.set_xlabel("spans holding each kind, baseline day 1")
top.legend(loc="lower right", fontsize=7.5)
save(fig, "personal-items-before-after")
```

Output:

```text
user_id spans before redaction: 200
user_id spans after redaction: 0
user_name spans before redaction: 2
user_name spans after redaction: 0
email spans before redaction: 0
email spans after redaction: 0
person slot spans before redaction: 38
person slot spans after redaction: 38
place_name slot spans before redaction: 33
place_name slot spans after redaction: 33
relation slot spans before redaction: 25
relation slot spans after redaction: 25
email_address slot spans before redaction: 0
email_address slot spans after redaction: 0
personal_info slot spans before redaction: 0
personal_info slot spans after redaction: 0
figure: figures/personal-items-before-after.svg
```

Figure 12.1 draws the spans on baseline day 1 that hold each kind of item, before and after redaction, in two panels. The top panel's synthetic kinds fall to nothing after redaction. The bottom panel's personal-looking values keep the bars they had before, 38 spans for person values before redaction and 38 after it. Each panel has its own scale, so compare bars within a panel and not across the two. The figure counts spans and the scan counts items, so the bottom panel's bars are smaller than the scan's counts for the same kinds, and both stay the same before and after redaction. In each pair, the second bar is the count after redaction.

*Figure 12.1. Spans holding each kind of personal item, before and after redaction, in two panels.*

![The synthetic users' items fall to nothing after redaction, and the dataset's personal-looking values keep their bars before and after.](https://rollingedition.ai/books/observability-for-llm-applications/2026.11.2/figures/personal-items-before-after.svg)

The 55 person values that redaction leaves measure how much of the request text the redactor cannot reach. That is a count of the redactor's reach, not of anyone's records, and a reader should not take it as one.

**Working rule:** Assert zero only for the kinds the redactor is built to remove, and print every other kind as a measure. A count the redactor cannot reach is a fact to report, and it does not count against the check that passed.

## Who may read what is left {#who-may-read-traces}

A trace that has been redacted still holds data, and who may read it matters as much as what the redactor removed. The rows that remain carry pseudonyms in place of user IDs, the slot values the redactor could not find, and any stack trace that a service wrote and no later step removed. [The content store](#keep-content-by-reference) holds the user's text whole. Reading a span is therefore a kind of reading personal data, even when the span holds no name.

We recommend giving each reader the rows their purpose needs. The people who answer an alert read the redacted rows, which carry the pseudonym, the route and the timing, and they do not need the content. The people who debug a named route may read the content, for the purpose named when capture was turned on, and for as long as that purpose lasts. The contacts team reads the spans of its own server, which it owns. Who reads which rows is enforced by the backend's access controls, and the book's receiver has none, so these rules hold only where the backend can restrict content attributes or the content store by role. We recommend a backend that can do that.

Keeping personal data out of a model's own context is a different job. In *Securing LLM Applications and Agents*, [hidden context](https://rollingedition.com/concepts/llm-security/hidden-context) is what a system prompt holds out of the user's view, such as secrets. This chapter is about what the telemetry holds after the model has run.

**Working rule:** Before you turn capture on, write down who may read the raw content, for what purpose and until when. Give every other reader the redacted rows, and apply the same rule to the content store.

## Keeping private data out in production {#keep-private-data-out-in-production}

The redaction in this chapter works on the case the book runs, and production differs in several ways. The redactor knows the case's names and matches them case-sensitively. Its address rule matches the `.example` domain. A real name or a real address passes straight through. The redactor also leaves the span's name, its resource, its links and its array values alone. A production team needs a detector for the data it holds, such as a [PII model](https://rollingedition.com/concepts/data-governance/pii-model) trained for personal data, and it should measure that detector's misses against labelled data, which this book does not have.

The stack-trace rule keys on one attribute name, `exception.stacktrace`. A traceback written under another name passes, and so does a path that appears in a message's text. The scanner counts stack traces as their own kind, so a team can count them after each release and see whether a new service has begun to write them.

The raw span also crosses the network before the receiver redacts it. The transport and the receiver's own logs hold the raw content for that moment, and they need the same care as the rest of the path. A receiver that redacts is safe only if nothing else on the path keeps what it received.

The pseudonym is only as private as its key. A key in the code, as this book uses, lets anyone who reads the code match candidate IDs, and a leaked key gives the same result. In production, draw the key as 32 random bytes from a secret store: [RFC 2104](https://www.rfc-editor.org/rfc/rfc2104#section-3) advises against an HMAC key shorter than the hash's output. Twelve hexadecimal digits suit the case's 200 users, but a large user base needs more digits, since at ten million users a shared pseudonym is no longer unlikely. Rotating the key starts every user's pseudonym again, so the change needs a plan.

The content store keeps the user's text whole, and its retention is its own. [Chapter 11](#retention) left the period to the team that runs the backend, and the store's period belongs to that team as well. A store with no period keeps the text for as long as it exists.

**Working rule:** After each release, run the scan on a day of traffic, and treat any kind that counts above zero after redaction as a finding until someone can say why it may remain. Count the stack traces and the items in the same scan, so that a new source of either shows up in one report.

## The decisions this chapter made {#keep-private-data-out-decisions}

A process can remove only what it writes, so each decision below puts its check where the output of every process lands.

- We keep content capture off in every service. Capture off still leaves a user ID on every message's root span, so the keyed pseudonym is part of the default and not an extra.
- We drop stack traces where every service's spans pass, which in this book is the receiver, and we recommend the same step in a production Collector. The contacts team should set `record_exception=False` on its lookup span, but we do not depend on that change to protect the data.
- We run redaction in each process for what that process writes, and again where every service's spans pass, and the stack traces show what that limit costs.
- We key the user pseudonyms with a secret that the telemetry's readers never hold. The demonstration key in the code shows the construction only.
- We keep content in a store only with access and retention rules of its own, since the upload hook writes whenever it is on, including for spans that sampling drops.
- We assert zero for the synthetic kinds that redaction removes, and we print the residue of the dataset's values as a measure of what the redactor cannot reach.
- We run the scan on every release's output, so that a new source of stack traces or items shows in one report.
