Sub topic 6
Context propagation and parent-child spans
This chapter assumes you can read the SDK setup from the earlier chapter (a TracerProvider, a processor and an exporter). It also assumes you know what a span is and have used with blocks in Python. Here you will learn how a new span finds its parent, why that link sometimes breaks, and how to carry a trace across threads and services.
What "context" means
A trace is a tree of spans that share a trace_id. Each span stores the span_id of its parent. Your code never passes these IDs around by hand. The SDK reads them from a context, an immutable key-value mapping that holds the currently active span.
In Python, OpenTelemetry stores the current context in a contextvars.ContextVar. When you start a span, the SDK does the following:
- It reads the current context and looks for an active span.
- If it finds one, the new span copies that span's
trace_idand records itsspan_idas the parent. - If it finds none, the new span becomes a root span with a new
trace_id.
This lookup is what turns a flat list of model calls and tool calls into a readable agent run.
Implicit parenting with start_as_current_span
start_as_current_span does two things. It creates the span, and it makes that span current for the duration of the with block. Any span started inside the block becomes a child. This is how the execute_tool span in the earlier agent example ends up under invoke_agent.
tracer.start_span() creates a span but does not make it current. Spans started afterwards will not become its children unless you pass the parent explicitly. Use start_as_current_span unless you need manual control over when the span ends.
Where context gets lost
The context lives in a ContextVar, so it follows the thread or task that set it. This causes most broken traces in agent code.
| Situation | Is context inherited? | What to do |
|---|---|---|
| Plain function calls in the same thread | Yes | Nothing |
| `asyncio.create_task`, `await` | Yes. Tasks copy the context when created. | Nothing |
| `asyncio.to_thread` | Yes. It copies the context. | Nothing |
| `ThreadPoolExecutor.submit` or `map` | No | Capture and attach the context yourself, or use the threading instrumentation |
| `loop.run_in_executor` | No | Capture and attach the context yourself |
| A new process, or an HTTP call to another service | No | Inject and extract headers |
When context is lost, the child span does not fail. It silently becomes a root span in a new trace. In your backend you see orphan traces such as a lone execute_tool span with no agent above it.
Passing context across threads
Agents often run tool calls in parallel. Capture the context in the parent thread, then attach it in the worker.
from concurrent.futures import ThreadPoolExecutor
from opentelemetry import context, trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
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")
def run_tool(name, parent_ctx):
token = context.attach(parent_ctx)
try:
with tracer.start_as_current_span(f"execute_tool {name}") as span:
span.set_attribute("gen_ai.operation.name", "execute_tool")
span.set_attribute("gen_ai.tool.name", name)
return name
finally:
context.detach(token)
def run_agent():
with tracer.start_as_current_span("invoke_agent support-agent") as agent:
ctx = context.get_current()
with ThreadPoolExecutor(max_workers=2) as pool:
names = list(pool.map(lambda n: run_tool(n, ctx), ["search_orders", "get_policy"]))
print("agent trace:", format(agent.get_span_context().trace_id, "032x"))
return names
if __name__ == "__main__":
run_agent()Both tool spans print the same trace_id as the agent span, and each has the agent's span_id as its parent_id. The try/finally matters. If you skip context.detach, the worker thread keeps the old context, and the next task on that thread can attach to the wrong parent.
The opentelemetry-instrumentation-threading package does this capture-and-attach step automatically for threading and concurrent.futures. Use it if you have many call sites.
Setting a parent explicitly
Sometimes you need a parent that is not current. Pass a context to the tracer:
parent_ctx = trace.set_span_in_context(parent_span)
child = tracer.start_span("retrieve documents", context=parent_ctx)
try:
...
finally:
child.end()Passing context= is also the way to build a span from an extracted remote context, shown next.
Crossing a service boundary
An agent often calls a tool server or another agent over HTTP. To keep one trace, the caller writes the trace identity into request headers, and the callee reads it back. The default propagator uses the W3C Trace Context standard, which defines the traceparent header. Its value looks like 00-<trace_id>-<parent_span_id>-<flags>.
from opentelemetry import propagate, trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.trace import SpanKind
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("support_agent")
def call_tool_server():
with tracer.start_as_current_span("POST /tools/refund", kind=SpanKind.CLIENT) as span:
headers = {}
propagate.inject(headers) # adds the traceparent header
handle_request(headers) # stands in for an HTTP request
return span.get_span_context().trace_id
def handle_request(headers):
ctx = propagate.extract(headers)
with tracer.start_as_current_span("refund", kind=SpanKind.SERVER, context=ctx) as span:
print("server trace:", format(span.get_span_context().trace_id, "032x"))
if __name__ == "__main__":
trace_id = call_tool_server()
print("client trace:", format(trace_id, "032x"))The two printed trace IDs match. In a real deployment the server runs in another process. HTTP client and server instrumentation libraries call inject and extract for you, but you must do it manually for message queues, custom protocols and subprocesses.
Span links for fan-in and batches
A parent-child relationship says "this work happened inside that work." Some cases do not fit. A background worker that processes a queue of agent requests in a batch, for example, has several causes. For these, keep one trace per cause and connect them with a link:
links = [trace.Link(request_span_context) for request_span_context in pending]
with tracer.start_as_current_span("process batch", links=links):
...Links must be supplied when the span is created. They show up in trace viewers as cross-references, not as tree nesting.
The shape you are aiming for
Debugging a broken tree
- Many one-span traces. Context was lost at a thread or executor boundary. Attach the captured context in the worker.
- Two traces for one request. A service did not extract headers, or a proxy removed
traceparent. Check the incoming headers on the second service. - Wrong parent. A
context.attachwithout a matchingdetachleaked a context into later work. Always usetry/finally. - Child outlives the parent. You called
start_spanwithout ending it, or a background task kept running after thewithblock exited. This is legal, but the durations will look odd. Consider a link instead.
Exercise
Your agent calls pool.submit(search_orders, "c-42") inside with tracer.start_as_current_span("invoke_agent ..."). In the backend, execute_tool search_orders shows up as a separate trace. Why, and what is the minimal fix?
Show answer
The worker thread has its own context, so it sees no active span and starts a new root span with a new traceid. Capture `ctx = context.getcurrent() in the parent thread, then in the worker call context.attach(ctx) before starting the span and context.detach(token) in a finally` block. Alternatively, install the threading instrumentation so this happens automatically.
Exercise
A tool server receives requests from your agent, but its spans never join the agent's trace. The client side already calls propagate.inject(headers). What should you check on the server side?
Show answer
Check that the server calls propagate.extract on the incoming request headers and passes the result as context= when starting its first span, or that its HTTP server instrumentation is installed. Also confirm that the traceparent header actually reaches the server and was not stripped by a proxy.