🐛 Bug Report: OpenAI Agents: uninstrument() leaves runs traced, and instrument() again records every span twice
Los mantenedores suelen responder en 1 día
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
- Área
- backend, observability
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
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de traceloop/openllmetry
-
🐛 Bug Report: OpenAI Responses: with_raw_response.create() raises when the body can't be parsed, though the uninstrumented call returnsPosiblemente ocupada Un pull request vinculado a esta issue está abierto o ya se fusionó. Abiertobug python
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
traceloop/openllmetry#4717 ·
Los mantenedores suelen responder en 1 día
-
🐛 Bug Report: Incomplete cache token migration after #4243 breaks Bedrock and Groq instrumentationPosiblemente ocupada @Quantum-Enigma-dot la tomó hace 21 días. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
traceloop/openllmetry#4665 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
🐛 Bug Report: OpenAI instrumentation drops gen_ai.usage.reasoning_tokens on streamed chat completionsPosiblemente ocupada @jayfeng7 la tomó hace 23 días. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
traceloop/openllmetry#4660 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
Bug Report: Failed dataset deletes still remove local rows and columnsPosiblemente ocupada @inchang-ing la tomó hace 32 días. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 88/100
traceloop/openllmetry#4630 ·
Los mantenedores suelen responder en 1 día
-
🐛 Bug Report: LiteLLM instrumentation does not record seed, stop, frequency_penalty, presence_penaltyPosiblemente ocupada @shantam77 la tomó hace 38 días. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 85/100
traceloop/openllmetry#4598 · 2 comentarios ·
Los mantenedores suelen responder en 1 día
Todos los issues de traceloop/openllmetry
Issues similares
-
CI flake: test-windows times out spawning Node in tests/test_antigravity_node_hooks.py (develop red)Abiertoarea/ci P2
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
Los mantenedores suelen responder en 2 días
-
benchmark
Dificultad 1/5 1-3 horas Aptitud para principiantes 72/100
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 79/100
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 77/100
mozilla-ai/cq#601 ·
Los mantenedores suelen responder en 1 día
-
Bump Python to 3.14 or 3.15Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
Los mantenedores suelen responder en 1 día