Sub topic 6
Context Propagation and Parent-Child Spans
This chapter assumes you can write basic Python with context managers and that you have set up the SDK as in the earlier setup chapter. It explains how spans find their parents, which is what turns a flat list of spans into a trace tree.
How a span gets its parent
Every span stores a trace ID, its own span ID, and the span ID of its parent. A span with no parent is the root of the trace. OpenTelemetry tracks the "current" span in a context, an immutable key-value store held per thread or per async task. In Python it uses contextvars.
When you call start_as_current_span, two things happen:
- The new span reads the current span from the context and uses it as its parent.
- The new span becomes the current span until the
withblock ends. Then the previous span is restored.
Nesting with blocks therefore builds the tree for you.
Nesting in practice
The tool call in the agent example needs no parent argument. It is called inside the agent span's with block, so it picks up that span automatically.
from opentelemetry import trace
tracer = trace.get_tracer("support_agent")
def search_orders(customer_id):
with tracer.start_as_current_span("execute_tool search_orders") as span:
span.set_attribute("gen_ai.operation.name", "execute_tool")
span.set_attribute("gen_ai.tool.name", "search_orders")
return [{"id": "A-1001", "customer": customer_id}]
def run_agent(question):
with tracer.start_as_current_span("invoke_agent support-agent") as span:
span.set_attribute("gen_ai.operation.name", "invoke_agent")
span.set_attribute("gen_ai.agent.name", "support-agent")
orders = search_orders("c-42")
return f"Found {len(orders)} order(s) for your question: {question}"The execute_tool span shares the agent's trace ID, and its parent ID is the agent span's ID. A backend uses these IDs to draw the tree.
Where context gets lost
Context follows the current thread or async task. It does not follow work you hand off by other means.
- Plain threads and thread pools. A new thread starts with an empty context, so spans created there become new root spans in separate traces. Capture the context with
context.get_current()and attach it in the worker withcontext.attach(). Detach it in afinallyblock. - Async code.
asynciotasks copy the context when they are created, so spans usually nest correctly. Check this when you use libraries that run work on their own executors. - Separate processes or services. The context cannot cross the network on its own. You must send it in headers.
Propagating across services
If your agent calls a tool served by another HTTP service, inject the context into the request headers. The receiving service extracts it and starts its spans as children. The default format is the W3C traceparent header, which carries the trace ID, the parent span ID, and a sampled flag.
from opentelemetry.propagate import inject, extract
from opentelemetry import trace
tracer = trace.get_tracer("support_agent")
def build_headers():
headers = {}
inject(headers) # adds the traceparent header
return headers
def handle_request(incoming_headers):
ctx = extract(incoming_headers)
with tracer.start_as_current_span("handle_tool_request", context=ctx):
return "ok"Most HTTP instrumentation libraries do this for you. Write it by hand only for custom transports such as message queues.
Exercise
A tool function runs in a ThreadPoolExecutor worker, and its span shows up as a separate root span in a new trace. Why does this happen, and how do you fix it?
Show answer
A new thread starts with an empty context, so no current span exists to act as the parent. Capture the context in the calling thread with context.get_current(), then call context.attach() with it inside the worker. Call context.detach() with the returned token in a finally block when the work ends.