🐛 Bug Report: OpenAI Agents: uninstrument() leaves runs traced, and instrument() again records every span twice
Maintainers usually reply within 1 day
Assessment
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Newbie friendliness
- 56/100
- Issue type
- Bug
- Clarity
- Clearly specified
- Activity status
- Active
- Tech stack
- python
- Domain
- backend, observability
Research direction
Start by reading OpenAIAgentsInstrumentor._instrument() and _uninstrument() in the OpenAI Agents instrumentation; the issue identifies processor registration and realtime session wrapper cleanup as the relevant paths. Reproduce the three instrument/run/uninstrument steps in the report and inspect the processor handling, including replace_existing_processors=True. Done means runs emit no spans after uninstrumenting and a second instrumentation records each span once.
Written by the indexing model from the issue text.
Description
Which component is this bug for?
OpenAI Instrumentation
📜 Description
OpenAIAgentsInstrumentor._instrument() registers an OpenTelemetryTracingProcessor with add_trace_processor()
(or with set_trace_processors() when replace_existing_processors=True), but _uninstrument() only unwraps the realtime
session wrappers. The processor stays registered, so runs are still traced after uninstrument(), and every further
instrument() adds another processor, so each span is recorded once per processor.
👟 Reproduction steps
# OpenAI Agents SDK: OpenAIAgentsInstrumentor().uninstrument() leaves runs traced, and instrument() again records
# every span twice.
import asyncio, gc, json, sys
from importlib.metadata import version
import openai
try:
import httpx2 as httpx # openai >= 3
except ImportError:
import httpx
from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
from agents import Agent, RunConfig, Runner, function_tool, set_default_openai_client, set_trace_processors
from opentelemetry.instrumentation.openai_agents import OpenAIAgentsInstrumentor
PKG = "opentelemetry-instrumentation-openai-agents"
class Spans(SpanProcessor):
def __init__(self): self.started, self.ended = {}, {}
def on_start(self, span, parent_context=None): self.started[span.context.span_id] = span
def on_end(self, span): self.ended[span.context.span_id] = span
def clear(self): self.started.clear(); self.ended.clear()
def never_ended(self): return sorted(s.name for k, s in self.started.items() if k not in self.ended)
spans = Spans(); provider = TracerProvider(); provider.add_span_processor(spans)
TURN = {}
def respond(request): # a local stand-in for the Responses API: a tool call, then text
body = json.loads(request.content)
run = body.get("instructions", "")
n = TURN[run] = TURN.get(run, 0) + 1
item = ({"type": "function_call", "id": f"fc_{n}", "call_id": f"call_{n}", "name": "lookup",
"arguments": json.dumps({"q": "weather"}), "status": "completed"} if n == 1 else
{"type": "message", "id": f"msg_{n}", "status": "completed", "role": "assistant",
"content": [{"type": "output_text", "annotations": [], "text": "It is sunny."}]})
resp = {"id": f"resp_{n}", "object": "response", "created_at": 0, "status": "completed", "model": "m",
"parallel_tool_calls": True, "tool_choice": "auto", "tools": [], "output": [item],
"usage": {"input_tokens": 3, "output_tokens": 2, "total_tokens": 5,
"input_tokens_details": {"cached_tokens": 0}, "output_tokens_details": {"reasoning_tokens": 0}}}
if not body.get("stream"):
return httpx.Response(200, json=resp)
events = [{"type": "response.created", "response": dict(resp, status="in_progress", output=[])},
{"type": "response.output_item.added", "output_index": 0,
"item": dict(item, status="in_progress", **({"content": []} if item["type"] == "message" else {"arguments": ""}))},
{"type": "response.output_item.done", "output_index": 0, "item": item},
{"type": "response.completed", "response": resp}]
text = "".join(f"event: {e['type']}\ndata: {json.dumps(dict(e, sequence_number=i))}\n\n" for i, e in enumerate(events))
return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=text.encode())
set_trace_processors([]) # no export to OpenAI
set_default_openai_client(openai.AsyncOpenAI(api_key="x", base_url="http://mock/v1", max_retries=0,
http_client=httpx.AsyncClient(transport=httpx.MockTransport(respond))), use_for_tracing=False)
@function_tool
def lookup(q: str) -> str:
"""Look something up."""
return "sunny"
def agent(run):
return Agent(name="assistant", instructions=run, model="m", tools=[lookup])
async def main():
print(f"{PKG} {version(PKG)} | "
f"openai-agents {version('openai-agents')} | python {sys.version.split()[0]}")
OpenAIAgentsInstrumentor().instrument(tracer_provider=provider)
spans.clear(); await Runner.run(agent("run 1"), "weather?", run_config=RunConfig(workflow_name="wf"))
print(f"1. instrumented, a run: {len(spans.ended)} spans")
OpenAIAgentsInstrumentor().uninstrument()
spans.clear(); await Runner.run(agent("run 2"), "weather?", run_config=RunConfig(workflow_name="wf"))
print(f"2. after uninstrument(), a run: {len(spans.ended)} spans")
OpenAIAgentsInstrumentor().instrument(tracer_provider=provider)
spans.clear(); await Runner.run(agent("run 3"), "weather?", run_config=RunConfig(workflow_name="wf"))
print(f"3. instrument() again, a run: {len(spans.ended)} spans")
asyncio.run(main())
👍 Expected behavior
After uninstrument() a run produces no spans (0 in line 2), and instrumenting again records each span once (5 in
line 3).
👎 Actual Behavior with Screenshots
opentelemetry-instrumentation-openai-agents 0.62.4 | openai-agents 0.24.0 | python 3.13.7
1. instrumented, a run: 5 spans
2. after uninstrument(), a run: 5 spans
3. instrument() again, a run: 10 spans
🤖 Python Version
3.13 (also seen with 3.12)
📃 Provide any additional context for the Bug.
_uninstrument() could remove the processor it registered (or turn it off), and restore the previous processors
when replace_existing_processors=True. opentelemetry-instrumentation-openai-agents 0.62.4 (the latest release; main has no changes to this package since), openai-agents 0.24.0 (also 0.23.1). Same symptom as #4552 (OpenAI instrumentation), with a different cause.
👀 Have you spent some time to check if this bug has been raised before?
- I checked and didn't find similar issue
Are you willing to submit PR?
None
- Dominant language
- Python
- Stars
- 7.5k
- Forks
- 1.2k
- Avg merge
- 2d 6h
- Merged PRs (30d)
- 2
Getting set up
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from traceloop/openllmetry
-
bug python
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
traceloop/openllmetry#4717 ·
Maintainers usually reply within 1 day
-
🐛 Bug Report: Incomplete cache token migration after #4243 breaks Bedrock and Groq instrumentationPossibly taken @Quantum-Enigma-dot claimed this 21 days ago. Open
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
traceloop/openllmetry#4665 · 1 comment ·
Maintainers usually reply within 1 day
-
🐛 Bug Report: OpenAI instrumentation drops gen_ai.usage.reasoning_tokens on streamed chat completionsPossibly taken @jayfeng7 claimed this 23 days ago. Open
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
traceloop/openllmetry#4660 · 1 comment ·
Maintainers usually reply within 1 day
-
Bug Report: Failed dataset deletes still remove local rows and columnsPossibly taken @inchang-ing claimed this 32 days ago. Open
Difficulty 2/5 1-3 hours Newbie friendliness 88/100
traceloop/openllmetry#4630 ·
Maintainers usually reply within 1 day
-
🐛 Bug Report: LiteLLM instrumentation does not record seed, stop, frequency_penalty, presence_penaltyPossibly taken @shantam77 claimed this 38 days ago. Open
Difficulty 2/5 1-3 hours Newbie friendliness 85/100
traceloop/openllmetry#4598 · 2 comments ·
Maintainers usually reply within 1 day
All issues in traceloop/openllmetry
Similar issues
-
opensubtitlescom: provider rejects pt-PT even though its own converter maps itPossibly taken @paulo-0308 claimed this today. Open
Difficulty 1/5 Under an hour Newbie friendliness 88/100
Diaoul/subliminal#1405 ·
-
Internal ErrorOpenbug
Difficulty 2/5 1-3 hours Newbie friendliness 66/100
frappe/frappe_docker#2071 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
The-Pocket/PocketFlow#161 ·
-
comp/desktop P2 type/bug
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
NousResearch/hermes-agent#157702 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 83/100
zai-org/zcode-plugins#202 ·
Maintainers usually reply within 1 day