Sub topic 12
Tracing retrieval in RAG pipelines
Retrieval-augmented generation (RAG) fetches documents from an index and puts them in the prompt before the model answers. When a RAG answer is wrong, the cause is often retrieval and not the model. A trace can show which one failed. This chapter covers how to model retrieval as spans and which attributes to record. It also covers the usual mistakes.
This chapter assumes you can already create spans with start_as_current_span, set attributes, and export spans through the SDK. It also assumes you know how a parent span nests its children. Earlier chapters covered those.
Why retrieval needs its own spans
If you only trace the model call, a bad answer gives you little to work with. You can't tell whether the retriever returned nothing, returned irrelevant text, or returned good text that the model ignored. Retrieval spans separate those cases.
Retrieval also has its own failure modes and costs:
- Latency. Vector search, reranking, and query embedding each take time. A slow answer may come from the index and not from the model.
- Quality. Low similarity scores, zero results, or the same document returned on every request all suggest a problem.
- Cost. Embedding calls to a hosted model use tokens. Without a span you won't see that usage.
The shape of a RAG trace
A typical RAG run has a parent agent or request span. Under it sit a retrieval span, an optional embedding span, an optional rerank span, and a final chat span. Spans for sequential steps are siblings. A span for a sub-step, such as the embedding done inside retrieval, is a child of the retrieval span.
Keeping retrieval's sub-steps under one span lets you read total retrieval time at a glance. You can then open the span to see where that time went.
Naming and attributes
The GenAI semantic conventions define a retrieval value for gen_ai.operation.name. They also define attributes such as gen_ai.data_source.id for naming the index or store. These conventions are still marked as in development, so check the current specification before you rely on a name. Anything the specification doesn't cover should go under your own namespace. This chapter uses app.retrieval.*, so a later spec change can't collide with it.
| Attribute | Type | Purpose |
|---|---|---|
| `gen_ai.operation.name` | string | `retrieval` or `embeddings`, so tools can classify the span |
| `gen_ai.data_source.id` | string | Which index or collection was searched |
| `app.retrieval.top_k` | int | How many results were requested |
| `app.retrieval.result_count` | int | How many were returned |
| `app.retrieval.top_score` | double | Best similarity score, to spot weak matches |
| `app.retrieval.query_length` | int | Query size, recorded without the query text |
Follow the span-naming pattern from earlier chapters: the operation name followed by the target, such as retrieval docs-index. Use SpanKind.CLIENT, because the search usually goes to another process or service.
Instrumenting a retriever
This example runs as written. It uses an in-memory corpus and keyword overlap as a stand-in for vector search, and it prints spans to the console. Replace the scoring with your vector store call in real code.
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.trace import SpanKind
provider = TracerProvider(resource=Resource.create({"service.name": "support-agent"}))
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("support_agent.rag")
DOCS = {
"refund-policy": "refunds are issued within 14 days of purchase",
"shipping": "orders ship within 2 business days",
"warranty": "hardware has a one year warranty",
}
def retrieve(query, top_k=2):
with tracer.start_as_current_span("retrieval docs-index", kind=SpanKind.CLIENT) as span:
span.set_attribute("gen_ai.operation.name", "retrieval")
span.set_attribute("gen_ai.data_source.id", "docs-index")
span.set_attribute("app.retrieval.top_k", top_k)
span.set_attribute("app.retrieval.query_length", len(query))
words = set(query.lower().split())
scored = sorted(
(
(len(words & set(text.split())) / max(len(words), 1), doc_id)
for doc_id, text in DOCS.items()
),
reverse=True,
)[:top_k]
span.set_attribute("app.retrieval.result_count", len(scored))
span.set_attribute("app.retrieval.top_score", scored[0][0] if scored else 0.0)
span.add_event(
"retrieval.results",
{
"app.document_ids": [doc_id for _, doc_id in scored],
"app.scores": [round(score, 3) for score, _ in scored],
},
)
return scored
def answer(question):
with tracer.start_as_current_span("invoke_agent support-agent") as span:
span.set_attribute("gen_ai.operation.name", "invoke_agent")
hits = retrieve(question)
return [doc_id for _, doc_id in hits]
if __name__ == "__main__":
print(answer("how many days for refunds"))Running it prints two spans. The retrieval docs-index span lists invoke_agent support-agent as its parent, which confirms the nesting.
Attributes versus events
The example puts summary values on the span as attributes and per-result detail in an event. Use that split because attributes describe the whole operation, while the event records what happened at a moment. Results fit the second case: a list of IDs and scores. Backends can filter and aggregate on attributes, so keep those values small and bounded.
Attribute values must be primitives or homogeneous lists of primitives. You can't attach a list of dictionaries. If you need per-document detail, flatten it into parallel lists, as in the example, or emit one event per document.
Embedding and reranking sub-spans
Give each model-backed step its own span. An embedding call is a model call, so it gets gen_ai.operation.name set to embeddings, a model name, and gen_ai.usage.input_tokens if your client reports it. A reranker that runs locally can use a plain internal span named rerank, with attributes for input count and output count. Start these spans inside the with block of the retrieval span, and the context makes them its children with no extra code.
Reranking is the step that most often hides a quality bug. Recording the count before and after it shows whether it is dropping everything useful.
Common errors
- Recording the full query and documents on every span. Queries can contain personal data, and documents can be large or confidential. Record lengths and IDs by default. Treat full text as an opt-in setting, as covered in the chapter on content capture.
- Putting large lists in attributes. Backends truncate or reject oversize values. An unbounded top-k list is the usual cause. Cap what you record.
- Marking an empty result as an error. Zero results is a valid outcome. Leave the status unset and record
app.retrieval.result_count = 0. SetERRORonly when the search call itself fails, such as a timeout or connection error. - Ending the retrieval span before the work finishes. With streaming or async clients, a span closed too early shows a misleading duration. Close it after the results are materialized.
- Losing the parent in worker threads. If retrieval runs in a thread pool, the current context doesn't carry over automatically. Pass the context explicitly, as covered in the context propagation chapter, or the retrieval span becomes a separate root trace.
- High-cardinality span names. Don't put the query in the span name. Use a fixed name and put variable data in attributes.
What to look for when debugging
Open a slow or wrong RAG trace and check these in order:
- Is there a retrieval span at all? If not, the code path skipped retrieval.
- Is
result_countzero, or istop_scorelow? The index or the query is the problem. - Do the document IDs in the event match what you expect for this question?
- How long did retrieval take compared with the chat span? That tells you where to optimize.
If retrieval looks healthy and the answer is still wrong, the problem is probably prompt assembly or the model, and you can look there next.
Exercise
A RAG trace shows a retrieval span with app.retrieval.result_count = 0, status unset, and a normal duration. A teammate wants to set the span status to ERROR. Should they? What should you record instead, and what would justify ERROR?
Show answer
No. The search ran correctly and found nothing, which is a valid outcome, so the status stays unset. The span already records result_count = 0, and you can alert on that attribute if empty results matter. You could also add app.retrieval.top_score = 0.0 and an event describing the filter used. ERROR is justified only when the search call fails, for example a timeout, a connection failure, or an exception from the vector store client. In that case call record_exception and set the status to ERROR.