Debug Missing or Fragmented Traces in Multi-Step AI Agents
In this article
When a multi-step AI agent produces missing or fragmented traces, it becomes nearly impossible to audit its decisions, reproduce failures, or prove compliance. This guide shows you how to systematically identify where traces break, fix the root causes, and set up reliable tracing for your agent pipelines. You'll learn practical debugging techniques that work across popular agent frameworks and custom implementations.
What You'll Need
- Access to your agent's codebase and deployment environment
- Logging infrastructure (e.g., stdout, log files, or a tracing backend like Jaeger or Zipkin)
- Ability to run the agent in a development or staging environment
- Basic familiarity with your agent framework's tracing APIs (e.g., LangChain, LlamaIndex, or custom decorators)
Step-by-Step
- Reproduce the problem with a minimal test case. Create a script that runs your agent with a simple, deterministic input. If possible, disable external APIs or use mocked responses. This isolates the tracing issue from network flakiness.
- Check if tracing is enabled at the framework level. Many frameworks (like LangChain) require an explicit tracer or callback handler. Verify that your agent is initialized with tracing enabled—e.g., passing a
callbackslist or setting an environment variable likeLANGCHAIN_TRACING_V2=true. - Inspect the trace export configuration. If you're sending traces to a backend, confirm the endpoint URL, API key, and sample rate are correct. A misconfigured exporter silently drops traces. Check the exporter's logs for errors.
- Add manual span creation around each agent step. If your framework doesn't automatically instrument every step, wrap each function call (e.g., tool invocation, LLM call, memory update) with a manual span. Use the framework's context manager or decorator to start and end spans.
- Verify that spans are closed properly. Unclosed spans (e.g., due to an exception or early return) cause fragmented traces. Use
try/finallyor the context manager pattern to ensure every span ends. Check for any code paths that bypass the normal completion. - Check for asynchronous context propagation. In async agents, traces can break if the context (like a trace ID) isn't propagated across
awaitpoints. Use the framework's async context variable support (e.g.,contextvarsin Python) or ensure the tracer is passed explicitly to each async task. - Examine the trace ID propagation across service boundaries. If your agent calls external services (APIs, databases, other microservices), ensure the trace ID is injected into outgoing requests (e.g., via
traceparentheader) and extracted from incoming requests. Without this, traces appear as separate fragments. - Test with a single-step agent. Temporarily reduce your agent to one step and confirm the trace appears. If it does, the issue is in multi-step orchestration. If not, the problem is in your basic tracing setup.
- Review the agent's control flow for branching. If your agent uses conditional logic (e.g., if-then-else or loops), ensure each branch has its own span. Missing spans in rarely-taken branches can make traces look incomplete.
- Use a trace viewer to visualize the data. Load your traces into a viewer (like Jaeger UI or LangSmith) and look for gaps in the timeline. Identify which step is missing or where the parent-child relationship breaks.
- Add logging as a fallback. If traces still fail, add structured logs (with a unique request ID) at each step. This helps correlate events even if the trace system drops data.
Common Mistakes
- Ignoring exceptions: If an exception occurs mid-step, the span may not be closed, leaving a dangling trace. Always use
finallyto close spans. - Mixing sync and async code: Using
asyncio.run()inside an async function can break context propagation. Stick to one concurrency model. - Forgetting to set the parent span: When creating child spans manually, you must pass the current span as the parent. Otherwise, they become root spans and appear as separate traces.
- Over-sampling: Setting a low sampling rate (e.g., 10%) means many traces are intentionally dropped. For debugging, set sampling to 100%.
- Using a different trace ID format: If your services expect a 128-bit hex ID but you generate a 64-bit one, the trace will be rejected or fragmented.
Tips
- Use environment-specific configuration: Enable full tracing in development, but use a lower sample rate in production to reduce overhead.
- Instrument at the highest level: Wrap the entire agent run in a single root span, then add child spans for each step. This makes it easier to see the whole picture.
- Add metadata to spans: Include step names, tool names, and input/output summaries. This makes traces much more useful for debugging.
- Test tracing in CI: Add a test that asserts each step creates a span. This catches regressions early.
- Monitor trace export errors: Set up alerts for exporter failures so you know when traces are being lost.
Troubleshooting
If you see no traces at all: Verify that the tracer is initialized and the exporter is configured. Check the exporter's logs for connection errors. Try sending a test trace manually.
If traces are fragmented (multiple root spans): This usually indicates a context propagation failure. Check if you're using a global variable to store the trace ID—that won't work in async or multi-threaded code. Use context variables or pass the trace ID explicitly.
If some steps are missing: Look for code paths that bypass the tracing wrapper. For example, if a step is called directly instead of through the framework's executor, it may not be instrumented. Add manual spans to those calls.
If traces are complete but not exported: Check the exporter's batch size and flush interval. Small batches may take time to appear. Also, ensure the exporter is shut down gracefully to flush pending data.
If traces appear but are very slow: The overhead of tracing might be causing timeouts. Reduce the amount of data captured (e.g., truncate large inputs/outputs) or increase the timeout for the agent.
Frequently Asked Questions
Why do my traces stop after the first step?
This often happens when the first step returns a value that is not properly passed to the next step, or when an exception occurs that isn't caught. Check if the second step is actually being executed—add a log statement to confirm.
How do I trace a multi-threaded agent?
Use a thread-local or context variable to store the trace ID. Most tracing libraries provide a way to bind the current span to a thread. Ensure each thread starts with the correct parent span.
Can I use OpenTelemetry for AI agents?
Yes, OpenTelemetry is language-agnostic and works with any framework. You can create spans manually or use auto-instrumentation if available. Many agent frameworks have OpenTelemetry integrations.
What is the difference between a trace and a span?
A trace is the entire end-to-end request flow, composed of multiple spans. A span is a single unit of work (e.g., one LLM call or tool execution) with a start and end time, plus metadata.
How do I debug traces that are missing in production but present in development?
Check if production has a different sampling rate or if the exporter endpoint is not accessible from the production network. Also, verify that environment variables for tracing are set correctly.
Is there a way to trace without modifying code?
Some frameworks support environment-variable-based tracing (e.g., LangChain's LANGCHAIN_TRACING_V2). For custom code, you may need to add minimal instrumentation, but you can use a decorator to wrap all functions automatically.