🐛 Bug Report: OpenAI instrumentation uninstrument() is a no-op: unwrap() is called with "module", "Class.method", so nothing is unwrapped; re-instrumenting doubles spans and can leave spans that never end
Which component is this bug for?
OpenAI Instrumentation
📜 Description
OpenAIInstrumentor().uninstrument() does not remove any wrapper. After uninstrument(), OpenAI calls are still traced; calling instrument() again stacks a second wrapper, so every call produces two spans, and for a stream left early (break inside a with block) one of the two stacked spans never ends.
Root cause: _uninstrument in opentelemetry/instrumentation/openai/v1/__init__.py calls
unwrap("openai.resources.chat.completions", "Completions.create")
opentelemetry.instrumentation.utils.unwrap(obj, attr) treats a string obj as a dotted path to the object that holds the attribute: it splits at the last dot, imports openai.resources.chat, takes completions (the module), then does getattr(module, "Completions.create"). A dotted attribute name never resolves, so unwrap silently returns. (wrap_function_wrapper("module", "Class.method", ...) does accept this form, which is likely why it looks right.)
Every call in _uninstrument uses this form (about 30). The same form also appears in the Agno (unwrap("agno.agent", "Agent.run"), ...) and LangChain (unwrap("langchain_core.callbacks", "BaseCallbackManager.__init__"), unwrap("langgraph.pregel", "Pregel.stream"), ...) instrumentations. The Anthropic instrumentation uses the working form unwrap(f"{package}.{object}", method).
👟 Reproduction steps
No API key needed (mock transport).
import gc, json, importlib.metadata as md
import httpx, openai, openai.resources.chat.completions as cc
from opentelemetry.sdk.trace import TracerProvider, SpanProcessor
from opentelemetry.instrumentation.openai import OpenAIInstrumentor
from opentelemetry.instrumentation.utils import unwrap
class Count(SpanProcessor):
started = ended = 0
def on_start(self, span, parent_context=None): Count.started += 1
def on_end(self, span): Count.ended += 1
provider = TracerProvider(); provider.add_span_processor(Count())
def chunk(d, f=None): return "data: " + json.dumps({"id": "c", "object": "chat.completion.chunk", "created": 0, "model": "m",
"choices": [{"index": 0, "delta": d, "finish_reason": f}]}) + "\n\n"
def handler(request):
if json.loads(request.content).get("stream"):
body = chunk({"role": "assistant", "content": "Hello"}) + chunk({"content": " there"}) + chunk({}, "stop") + "data: [DONE]\n\n"
return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=body.encode())
return httpx.Response(200, json={"id": "c1", "object": "chat.completion", "created": 0, "model": "m",
"choices": [{"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": "Hi!"}}],
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}})
client = openai.OpenAI(api_key="x", base_url="http://mock/v1", http_client=httpx.Client(transport=httpx.MockTransport(handler)))
M = [{"role": "user", "content": "hi"}]
def report(label):
gc.collect(); print(f"{label:58s} spans started {Count.started}, ended {Count.ended}"); Count.started = Count.ended = 0
print("versions:", md.version("opentelemetry-instrumentation-openai"), "openai", md.version("openai"))
original = cc.Completions.create
inst = OpenAIInstrumentor()
inst.instrument(tracer_provider=provider)
inst.uninstrument()
print("Completions.create restored after uninstrument():", cc.Completions.create is original)
client.chat.completions.create(model="m", messages=M); report("1 call after instrument + uninstrument (expected 0)")
inst.instrument(tracer_provider=provider)
client.chat.completions.create(model="m", messages=M); report("1 call after re-instrument (expected 1)")
with client.chat.completions.create(model="m", messages=M, stream=True) as s:
for c in s: break
report("1 streamed call, break inside a with-block (expected 1/1)")
unwrap("openai.resources.chat.completions.Completions", "create"); unwrap("openai.resources.chat.completions.Completions", "create")
print("restored with unwrap('openai.resources.chat.completions.Completions', 'create') x2:", cc.Completions.create is original)
👍 Expected behavior
After uninstrument(), the original SDK methods are restored and calls produce no spans. Instrumenting again produces exactly one span per call, and that span ends. This is what BaseInstrumentor's instrument/uninstrument contract implies, and what openinference-instrumentation-openai and opentelemetry-instrumentation-genai-openai do in the same test.
👎 Actual Behavior with Screenshots
versions: 0.62.4 openai 2.54.0 Completions.create restored after uninstrument(): False 1 call after instrument + uninstrument (expected 0) spans started 1, ended 1 1 call after re-instrument (expected 1) spans started 2, ended 2 1 streamed call, break inside a with-block (expected 1/1) spans started 2, ended 1 restored with unwrap('openai.resources.chat.completions.Completions', 'create') x2: True
The last line shows the fix: unwrap with the class in the dotted path restores the original (twice, because re-instrumenting stacked two wrappers).
Practical impact:
- Tracing cannot be switched off at runtime (per-test setup/teardown, feature flags).
- Any code path that calls uninstrument() then instrument() (test fixtures, re-initialising the SDK) silently duplicates every OpenAI span, doubling span volume and any token or cost totals computed from spans.
- With stacked wrappers, a stream left early inside a
withblock leaves one span that is never ended, so it is never exported.
🤖 Python Version
3.12
📃 Provide any additional context for the Bug.
Versions: opentelemetry-instrumentation-openai 0.62.4 (also on main), openai 2.54.0.
Suggested fix: pass the class in the dotted path and only the method name as attr, e.g.
unwrap("openai.resources.chat.completions.Completions", "create")
for each entry in _uninstrument, and the same change in the Agno and LangChain instrumentations. A regression test could assert that Completions.create is the original function after instrument() + uninstrument().
👀 Have you spent some time to check if this bug has been raised before?
- [x] I checked and didn't find similar issue
Are you willing to submit PR?
Yes I am willing to submit a PR!
The same in opentelemetry-instrumentation-ollama 0.62.4 (ollama 0.6.3): after OllamaInstrumentor().uninstrument(), chat calls are still traced.
import httpx, ollama
from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
from opentelemetry.instrumentation.ollama import OllamaInstrumentor
class Count(SpanProcessor):
n = 0
def on_end(self, span): Count.n += 1
provider = TracerProvider(); provider.add_span_processor(Count())
OllamaInstrumentor().instrument(tracer_provider=provider)
client = ollama.Client(host="http://mock", transport=httpx.MockTransport(lambda r: httpx.Response(200, json={
"model": "m", "created_at": "2026-01-01T00:00:00Z", "done": True, "done_reason": "stop",
"message": {"role": "assistant", "content": "Hello"}})))
OllamaInstrumentor().uninstrument()
client.chat(model="m", messages=[{"role": "user", "content": "hi"}])
print("spans after uninstrument():", Count.n)
spans after uninstrument(): 1
The LangChain instrumentation has the same problem: _uninstrument() calls unwrap("langchain_core.callbacks", "BaseCallbackManager.__init__"), so the callback manager stays wrapped and LangGraph sessions are still traced after LangchainInstrumentor().uninstrument() (opentelemetry-instrumentation-langchain 0.62.4, langgraph 1.2.16, langchain-core 1.6.12):
# LangChain: after LangchainInstrumentor().uninstrument(), LangGraph sessions are still traced.
import sys
from importlib.metadata import version
from typing import Annotated
from typing_extensions import TypedDict
try:
import httpx2 as httpx # openai >= 3
except ImportError:
import httpx
from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
from opentelemetry.instrumentation.langchain import LangchainInstrumentor
class Spans(SpanProcessor):
def __init__(self): self.ended = []
def on_end(self, span): self.ended.append(span)
spans = Spans(); provider = TracerProvider(); provider.add_span_processor(spans)
LangchainInstrumentor().instrument(tracer_provider=provider)
from langchain_openai import ChatOpenAI
from langgraph.graph import END, START, StateGraph
from langgraph.graph.message import add_messages
def reply(request): # a local stand-in for the OpenAI API
return httpx.Response(200, json={"id": "c-1", "object": "chat.completion", "created": 0, "model": "gpt-4o-mini",
"choices": [{"index": 0, "message": {"role": "assistant", "content": "Paris."}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 3, "completion_tokens": 1, "total_tokens": 4}})
llm = ChatOpenAI(model="gpt-4o-mini", api_key="x", base_url="http://mock/v1", max_retries=0,
http_client=httpx.Client(transport=httpx.MockTransport(reply)))
class State(TypedDict):
messages: Annotated[list, add_messages]
g = StateGraph(State)
g.add_node("agent", lambda state: {"messages": [llm.invoke(state["messages"])]})
g.add_edge(START, "agent"); g.add_edge("agent", END)
graph = g.compile()
print(f"opentelemetry-instrumentation-langchain {version('opentelemetry-instrumentation-langchain')} | "
f"langgraph {version('langgraph')} | langchain-core {version('langchain-core')} | python {sys.version.split()[0]}")
graph.invoke({"messages": [("user", "Capital of France?")]})
print(f"instrumented, a session: {len(spans.ended)} spans")
LangchainInstrumentor().uninstrument()
spans.ended.clear()
graph.invoke({"messages": [("user", "Capital of France?")]})
print(f"after uninstrument(), a session: {len(spans.ended)} spans")
opentelemetry-instrumentation-langchain 0.62.4 | langgraph 1.2.16 | langchain-core 1.6.12 | python 3.13.7
instrumented, a session: 4 spans
after uninstrument(), a session: 4 spans