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

Abierto
#4,634 3 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

@anishgurjar ya está trabajando en esto.

Desde el 21/10/2026.

  • #4651 de @anishgurjar — abierto

Evaluación

Dificultad
3/5
Tiempo estimado
1-2 días
Aptitud para principiantes
56/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python

Línea de trabajo

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.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

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

Lenguaje dominante
Python
Estrellas
7.5k
Forks
1.2k
Merge medio
1 d 23 h
PR fusionados (30 d)
3

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de traceloop/openllmetry

Todos los issues de traceloop/openllmetry

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.