OpenTelemetry Spans for Test and Agent Runs, Not Just Prod
Most teams instrument production services with OpenTelemetry and stop at the CI boundary. The suite runs, JUnit XML is archived, and the only signal is pass/fail plus a wall-clock duration. That is a blind spot: a test suite is a distributed system in its own right. It fans out across workers, hits real databases, makes HTTP calls and accumulates latency variance nobody measures.
The blind spot grows in agentic quality engineering. Coding agents now run test suites themselves, sometimes many times while working on a single change, and they read the results to decide what to do next. If the only output is pass/fail and a stack trace, the agent and the engineer reviewing its work are both guessing. Spans from the test run give both of them the same structured evidence: which test, which fixture, which call, how long, and under which run.
This article explains trace-based testing and where it fits, how to emit spans from pytest and send them to Grafana Tempo, where span lifecycle and parallel workers break things, and how to attribute test-run traces to the agent that triggered them.
Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.
Trace-Based Testing: What It Means and Where It Fits
Trace-based testing means treating a test run as a traceable unit of work: the suite runner is the root span, each test case is a child span, and any I/O the test performs — DB queries, HTTP calls, queue publishes — is a nested grandchild span. The W3C TraceContext propagation header ties them all together. This is distinct from using distributed tracing to diagnose test failures in production-mirrored environments; here we're instrumenting the test process itself, not just the system under test.
In a modern CI architecture — GitHub Actions matrix jobs, Pytest-xdist workers, Playwright shards — this matters because test execution is already distributed. Without spans, you cannot answer "which shard is consistently slower?" or "does fixture setup account for more than 40% of total suite time?" Those are the questions that drive real pipeline optimization. The telemetry belongs in the same backend you use for services: Tempo, Honeycomb, or Datadog APM. Keeping it separate from a bespoke JUnit dashboard means your on-call engineers already know the query language.
Emitting Spans from Pytest and Wiring Them to Tempo
The fastest path in Python is the opentelemetry-sdk package plus a Pytest plugin hook. Install opentelemetry-sdk, opentelemetry-exporter-otlp-proto-grpc, and optionally pytest-opentelemetry, a plugin that wraps each test item as a child span. For suites that need finer control — fixture-level spans, parametrize attribution — wire it manually via conftest.py:
# conftest.py
import pytest
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
provider = TracerProvider()
provider.add_span_processor(
BatchSpanProcessor(OTLPSpanExporter(endpoint="http://tempo:4317", insecure=True))
)
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("pytest.suite")
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_protocol(item, nextitem):
with tracer.start_as_current_span(item.nodeid) as span:
span.set_attribute("test.file", str(item.path))
worker = getattr(item.config, "workerinput", {}).get("workerid", "main") # set only under xdist
span.set_attribute("test.worker", worker)
yield # pytest runs setup, call and teardown here
# status set in pytest_runtest_logreport hook
Add a pytest_runtest_logreport hook to attach outcome and exception info as span attributes (test.status, test.exception.type, test.exception.message). Keep attribute names consistent: OpenTelemetry's semantic conventions include a small, still-developing set of test attributes (such as test.case.name and test.case.result.status), and following them, or at least one internal convention, lets you filter in TraceQL without custom parsing.
On the GitHub Actions side, inject the OTLP endpoint as an environment variable and pass the CI run ID as a resource attribute so every span from a single pipeline run shares a common ci.run_id:
# .github/workflows/test.yml (relevant fragment)
env:
OTEL_EXPORTER_OTLP_ENDPOINT: "https://tempo.internal:4317"
OTEL_RESOURCE_ATTRIBUTES: "ci.run_id=${{ github.run_id }},ci.branch=${{ github.ref_name }},service.name=pytest-suite"
OTEL_EXPORTER_OTLP_HEADERS: "Authorization=Bearer%20${{ secrets.TEMPO_TOKEN }}" # header values are URL-encoded
Once spans land in Tempo, a TraceQL query surfaces slow tests immediately — no custom dashboard required on day one:
{ resource.service.name = "pytest-suite" && span.test.status = "failed" }
| select(span.test.file, span.test.exception.type)
The result lists failing test spans with the selected attributes and their durations; sort or filter further in Grafana's results table. The trace shows exactly which fixture or downstream call inflated the duration, rather than forcing an engineer to grep through thousands of lines of log output. For deeper analysis of how Tempo surfaces slow test runs across shards, the query patterns extend naturally from what you're already building here.
Where This Breaks in Practice: Span Lifecycle and Parallel Workers
The most common mistake is losing spans at the end of the run. BatchSpanProcessor exports in the background, so if the pytest process exits before the last batch is sent, the final tests and any teardown spans (dropping test databases, revoking tokens) never arrive. The fix is to call provider.force_flush() (or provider.shutdown()) inside a pytest_sessionfinish hook, not at module import time. Skipping this means traces in Tempo are missing their last spans, and duration data for suites with heavy teardown is quietly incomplete.
The second pitfall is context propagation across Pytest-xdist workers. Each worker is a separate process; the root span created in the controller process does not automatically propagate its trace_id to workers. You have to serialize the SpanContext and pass it through xdist's workerinput dict, then reconstruct a non-recording parent span on the worker side using trace.NonRecordingSpan. Teams that skip this end up with disconnected trace fragments — a problem well-documented in parallel test trace coverage gaps — and lose the ability to correlate worker-level failures back to the suite root span.
Tracing test runs triggered by coding agents
When a coding agent such as Copilot, Claude Code or Cursor runs the suite as part of its work, each run is a test session like any other, and the instrumentation above captures it. What is missing is attribution. Add resource attributes that say who ran the suite and why, so agent runs can be separated, compared and counted:
# set by the agent's task runner or CI job before invoking pytest
export OTEL_RESOURCE_ATTRIBUTES="service.name=pytest-suite,ci.triggered_by=agent,agent.task_id=${AGENT_TASK_ID},vcs.ref=${BRANCH}"
With that in place, TraceQL can answer questions about agent behaviour that are otherwise invisible:
{ resource.ci.triggered_by = "agent" && span.test.status = "failed" }
| count() > 3
That finds agent-triggered traces with more than three failing test spans, which is a quick way to spot sessions where the agent was iterating against a broken suite rather than converging. Grouping traces by agent.task_id shows how many suite runs a task took before it went green, which is both a cost figure and a signal about how well the agent understands the code.
Two practices make these traces useful in review. First, link the final green run's trace from the pull request the agent opens, so the reviewer can see what was actually executed, not just the agent's summary of it. Second, if the agent is allowed to modify tests, compare the set of test spans in its first and last runs. Tests that disappeared, or that began emitting a skip status, deserve a human look before merge. Repository instruction files such as .github/copilot-instructions.md or CLAUDE.md are a good place to state that skipping or deleting tests to get green is not allowed. For parallel-run gaps, see why trace coverage drops in parallel test runs.
Myths About Logs and Traces in Test Automation
Myth 1: "We have logs, so we have observability." Logs from a test run are flat events. They tell you what happened but not how long it took, what called what, or whether two failures share a causal ancestor. Spans give you duration, parent-child causality, and a shared trace_id that lets you join test execution data with the service traces it triggered — something no log aggregator in Loki or Splunk can reconstruct after the fact. Myth 2: "Pass/fail plus duration is enough signal." It isn't. A test that passes in 4.2 seconds when its P95 baseline is 800ms is telling you something is wrong with the environment, the data fixture, or a downstream dependency. Test results carry far more signal than pass/fail once you start measuring runtime variance across spans.
Myth 3: "OpenTelemetry instrumentation is too expensive to add to tests." The export overhead of a BatchSpanProcessor is small for most suites, because spans are batched and sent in the background; measure it on your own suite rather than assuming. The real cost is the one-time setup of propagation across workers. Teams that defer it because it "seems complex" are trading a modest setup effort against months of slow, context-free triage.
Start with a single Pytest suite, emit spans to a local Tempo instance via Docker Compose, and run the TraceQL query above against one week of CI history. The slow-fixture candidates will be obvious within the first query. From there, extend span attributes to cover retry counts and fixture names — that data feeds directly into pipeline pass-rate drift analysis and gives you the causal layer that JUnit XML alone will never provide.
Note: This article is for informational purposes only and is not a substitute for professional advice. If you need guidance on specific situations described in this article, consider consulting a qualified professional.