Bug Report: OpenAI instrumentation: ChatStream does not end the span on close() (sync or async)

Author: armanunixCreated Sep 30, 2026Updated Oct 1, 2026

Which component is this bug for?

OpenAI Instrumentation

Description

When an application reads part of a streamed chat completion and then calls stream.close() (sync) or await stream.close() (async), the LLM span is not ended. It stays open until the stream object is garbage-collected, where ChatStream.__del__ ends it.

Consequences: Wrong duration: The span ends when the object happens to be released, not when the call finished. In my test, closing and then releasing the stream 0.5 s later produced a span ending 0.50 s after close().

Spans stay open indefinitely: while the application keeps a reference to the stream (for example, in agent state or an exception traceback).

Spans are lost at shutdown.: If the stream is still referenced at interpreter exit, the span ends after the span processor has shut down and is dropped (Processor is already shutdown, ignoring call).

Root cause ChatStream calls _ensure_cleanup() from __exit__ and __del__ (added for #3151 in #3155), but it does not define close(). stream.close() is forwarded by the proxy straight to the OpenAI SDK's Stream.close() / AsyncStream.close(), so cleanup never runs.

Reproduction steps

python
import asyncio, gc, json, httpx, openai
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.instrumentation.openai import OpenAIInstrumentor

def sse():
    def c(d, f): return {"id": "c1", "object": "chat.completion.chunk", "created": 0, "model": "m",
                         "choices": [{"index": 0, "delta": d, "finish_reason": f}]}
    ev = "".join(f"data: {json.dumps(c({'content': p}, None))}\n\n" for p in ["Hel", "lo", "!"])
    return (ev + f"data: {json.dumps(c({}, 'stop'))}\n\ndata: [DONE]\n\n").encode()

transport = httpx.MockTransport(lambda r: httpx.Response(
    200, headers={"content-type": "text/event-stream"}, content=sse()))

exporter = InMemorySpanExporter()
provider = TracerProvider(); provider.add_span_processor(SimpleSpanProcessor(exporter))
OpenAIInstrumentor().instrument(tracer_provider=provider)
kwargs = dict(model="m", messages=[{"role": "user", "content": "hi"}], stream=True)

# Sync: read one chunk, then close() while the app still holds the stream
client = openai.OpenAI(api_key="x", base_url="http://mock/v1",
                       http_client=httpx.Client(transport=transport))
stream = client.chat.completions.create(**kwargs)
next(iter(stream)); stream.close()
print("sync close():   spans ended =", len(exporter.get_finished_spans()))  # expected 1, actual 0
del stream; gc.collect()
print("after release:  spans ended =", len(exporter.get_finished_spans()))  # 1, ended by __del__

# Async: read one chunk, then await close()
async def main():
    exporter.clear()
    aclient = openai.AsyncOpenAI(api_key="x", base_url="http://mock/v1",
                                 http_client=httpx.AsyncClient(transport=transport))
    s = await aclient.chat.completions.create(**kwargs)
    await s.__aiter__().__anext__(); await s.close()
    print("async close():  spans ended =", len(exporter.get_finished_spans()))  # expected 1, actual 0
asyncio.run(main())

Output:

sync close():   spans ended = 0
after release:  spans ended = 1
async close():  spans ended = 0

Expected behavior

Exactly one span has ended immediately after close() / await close(), as it already does when leaving a sync with block.

Actual Behavior with Screenshots

sync close():   spans ended = 0
after release:  spans ended = 1
async close():  spans ended = 0

Spans ended while the app still holds a reference to the stream, across lifecycle paths:

Path 0.62.4 / current main PR #4429
full iteration 1 1
sync with exit 1 1
sync close() 0 0
async with exit 0 1
async await close() 0 0

Python Version

3.12

Provide any additional context for the Bug.

Related

  • #3151 / #3155: added cleanup for non-consumed streams via __exit__ / __del__, but not close().
  • #4429 (open): fixes async with (__aexit__) but not close().
  • #4394 (open): the same problem in the legacy Completions wrappers; ChatStream is out of its scope.

Suggested fix: define close on ChatStream so it calls _ensure_cleanup() after closing the wrapped stream. AsyncStream.close() is a coroutine, so the async case must await it first:

python
def close(self):
    result = self.__wrapped__.close()
    if inspect.isawaitable(result):          # AsyncStream.close() is async
        async def _close_then_cleanup():
            try:
                return await result
            finally:
                self._ensure_cleanup()
        return _close_then_cleanup()
    self._ensure_cleanup()
    return result

Environment: opentelemetry-instrumentation-openai 0.62.4 and main as of 2026-09-30; openai 2.54.0; opentelemetry-sdk 1.45.0; Python 3.12; Ubuntu 24.04.

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?

Yes I am willing to submit a PR!