🐛 Bug Report: OpenAI Agents: uninstrument() leaves runs traced, and instrument() again records every span twice

Open
#4,634 3 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

@anishgurjar is already working on this.

Since Oct 21, 2026.

  • #4651 by @anishgurjar — open

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

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

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from traceloop/openllmetry

All issues in traceloop/openllmetry

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.