🐛 Bug Report: openai, anthropic, google-generativeai: a call cancelled while waiting for the response (asyncio timeout/cancel, Ctrl-C) never ends its span
I maintainer di solito rispondono entro 1 giorno
Valutazione
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Idoneità per principianti
- 58/100
- Tipo di issue
- Bug
- Chiarezza
- Specificata chiaramente
- Stato di attività
- Attiva
- Stack tecnologico
- python
- Ambito
- observability
Direzione di ricerca
Start with the cited wrappers in chat_wrappers.py, completion_wrappers.py, and embeddings_wrappers.py, then compare the Anthropic and Google Generative AI wrappers identified in the issue. Check how MCP session span cancellation was handled in #4517 and run the supplied async timeout reproducer for each SDK. Done means cancelled or interrupted calls end their spans as errors, propagate the exception unchanged, and have regression coverage.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
Which component is this bug for?
All Packages
📜 Description
When a call is cancelled while it waits for the server (for example asyncio.wait_for(...) times out, the task is cancelled, or the user presses Ctrl-C), the LLM span is never ended. An unended span is never exported, so the call disappears from the trace, even though the request was sent and may be billed.
The wrappers start the span with tracer.start_span(...) and end it only in except Exception or after a successful response. asyncio.CancelledError and KeyboardInterrupt are BaseException, so they pass through without ending the span:
- openai
chat_wrapper/achat_wrapper: L104, L203 (same pattern incompletion_wrappers.pyandembeddings_wrappers.py) - anthropic
_wrap/_awrap: L569, L701 - google-generativeai
_awrap/_wrap: L261, L340
Both streaming and non-streaming calls are affected, because the cancellation happens before the stream object exists. The same fix was made for the MCP session span in #4517.
👟 Reproduction steps
pip install openai anthropic google-genai opentelemetry-sdk opentelemetry-instrumentation-openai opentelemetry-instrumentation-anthropic opentelemetry-instrumentation-google-generativeai
python repro.py openai
python repro.py anthropic
python repro.py google
import asyncio, gc, logging, sys
from importlib.metadata import version
import httpx
from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
logging.disable(logging.WARNING)
SDK = sys.argv[1] if len(sys.argv) > 1 else "openai"
class Spans(SpanProcessor):
def __init__(self): self.open, self.ended = set(), []
def on_start(self, span, parent_context=None): self.open.add(span.context.span_id)
def on_end(self, span):
self.open.discard(span.context.span_id)
self.ended.append(f"{span.name} [{span.status.status_code.name}]")
spans = Spans()
provider = TracerProvider()
provider.add_span_processor(spans)
def slow_http(hx=httpx): # a server that answers after 5 s
async def slow_server(request):
await asyncio.sleep(5)
return hx.Response(200, json={})
return hx.AsyncClient(transport=hx.MockTransport(slow_server))
M = [{"role": "user", "content": "hi"}]
if SDK == "openai":
import openai
from opentelemetry.instrumentation.openai import OpenAIInstrumentor
OpenAIInstrumentor().instrument(tracer_provider=provider)
client = openai.AsyncOpenAI(api_key="x", base_url="http://mock/v1", max_retries=0, http_client=slow_http())
calls = {"create": lambda: client.chat.completions.create(model="m", messages=M),
"create(stream=True)": lambda: client.chat.completions.create(model="m", messages=M, stream=True)}
pkg = ("openai", "opentelemetry-instrumentation-openai")
elif SDK == "anthropic":
import anthropic, anthropic._base_client as base
from opentelemetry.instrumentation.anthropic import AnthropicInstrumentor
AnthropicInstrumentor().instrument(tracer_provider=provider)
hx = getattr(base, "httpx2", None) or httpx # newer anthropic releases use httpx2
client = anthropic.AsyncAnthropic(api_key="x", base_url="http://mock", max_retries=0, http_client=slow_http(hx))
calls = {"create": lambda: client.messages.create(model="m", max_tokens=50, messages=M),
"create(stream=True)": lambda: client.messages.create(model="m", max_tokens=50, messages=M, stream=True)}
pkg = ("anthropic", "opentelemetry-instrumentation-anthropic")
else:
from google import genai
from google.genai import types
from opentelemetry.instrumentation.google_generativeai import GoogleGenerativeAiInstrumentor
GoogleGenerativeAiInstrumentor().instrument(tracer_provider=provider)
client = genai.Client(api_key="x", http_options=types.HttpOptions(base_url="http://mock", httpx_async_client=slow_http()))
calls = {"generate_content": lambda: client.aio.models.generate_content(model="m", contents="hi"),
"generate_content_stream": lambda: client.aio.models.generate_content_stream(model="m", contents="hi")}
pkg = ("google-genai", "opentelemetry-instrumentation-google-generativeai")
async def main():
print(" | ".join(f"{p} {version(p)}" for p in pkg))
for name, call in calls.items():
spans.ended.clear()
try:
await asyncio.wait_for(call(), timeout=1.0) # the app gives up after 1 s
except TimeoutError:
pass
gc.collect()
await asyncio.sleep(0.1)
print(f"{name:25} timed out -> ended spans: {spans.ended or 'none'}; spans never ended: {len(spans.open)}")
spans.open.clear()
asyncio.run(main())
The sync clients behave the same way when the call is interrupted with Ctrl-C (KeyboardInterrupt) while waiting for the response.
👍 Expected behavior
The span ends with status ERROR and the exception (CancelledError / KeyboardInterrupt) recorded. The exception still propagates to the caller unchanged.
Suggested fix: catch BaseException instead of Exception around the wrapped call (or end the span in a finally block).
👎 Actual Behavior with Screenshots
The span is never ended, so it is never exported:
openai 3.26.0 | opentelemetry-instrumentation-openai 0.62.4
create timed out -> ended spans: none; spans never ended: 1
create(stream=True) timed out -> ended spans: none; spans never ended: 1
anthropic 1.11.0 | opentelemetry-instrumentation-anthropic 0.62.4
create timed out -> ended spans: none; spans never ended: 1
create(stream=True) timed out -> ended spans: none; spans never ended: 1
google-genai 2.28.0 | opentelemetry-instrumentation-google-generativeai 0.62.4
generate_content timed out -> ended spans: none; spans never ended: 1
generate_content_stream timed out -> ended spans: none; spans never ended: 1
🤖 Python Version
3.12
📃 Provide any additional context for the Bug.
The span-ending gap is in the request wrappers. A stream that is cancelled in the middle of reading is also not recorded as an error: the stream wrappers catch only Exception as well.
👀 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!
- Lingua principale
- Python
- Stelle
- 7.5k
- Fork
- 1.2k
- Merge medio
- 2g 6h
- PR unite (30g)
- 2
Preparare l'ambiente
- Nessun Dockerfile né file Docker Compose
- Ha un modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di traceloop/openllmetry
-
🐛 Bug Report: OpenAI Responses: with_raw_response.create() raises when the body can't be parsed, though the uninstrumented call returnsForse già presa Una pull request collegata a questa issue è aperta o già unita. Apertabug python
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
traceloop/openllmetry#4717 ·
I maintainer di solito rispondono entro 1 giorno
-
🐛 Bug Report: Incomplete cache token migration after #4243 breaks Bedrock and Groq instrumentationForse già presa @Quantum-Enigma-dot l’ha presa 21 giorni fa. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
traceloop/openllmetry#4665 · 1 commento ·
I maintainer di solito rispondono entro 1 giorno
-
🐛 Bug Report: OpenAI instrumentation drops gen_ai.usage.reasoning_tokens on streamed chat completionsForse già presa @jayfeng7 l’ha presa 23 giorni fa. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 82/100
traceloop/openllmetry#4660 · 1 commento ·
I maintainer di solito rispondono entro 1 giorno
-
Bug Report: Failed dataset deletes still remove local rows and columnsForse già presa @inchang-ing l’ha presa 32 giorni fa. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 88/100
traceloop/openllmetry#4630 ·
I maintainer di solito rispondono entro 1 giorno
-
🐛 Bug Report: LiteLLM instrumentation does not record seed, stop, frequency_penalty, presence_penaltyForse già presa @shantam77 l’ha presa 38 giorni fa. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 85/100
traceloop/openllmetry#4598 · 2 commenti ·
I maintainer di solito rispondono entro 1 giorno
Tutte le issue di traceloop/openllmetry
Issue simili
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 77/100
mozilla-ai/cq#601 ·
I maintainer di solito rispondono entro 1 giorno
-
Bump Python to 3.14 or 3.15Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 68/100
I maintainer di solito rispondono entro 1 giorno
-
intcomma returns exponential notation for large floatsForse già presa @Omarinho12345 l’ha presa oggi. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
python-humanize/humanize#521 ·
I maintainer di solito rispondono entro 1 giorno
-
LUCJ pass manager raises NoEdgeBetweenNodes when an edge is bad for two two-qubit gatesForse già presa @hat-im l’ha presa oggi. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
I maintainer di solito rispondono entro 1 giorno
-
opensubtitlescom: provider rejects pt-PT even though its own converter maps itForse già presa @paulo-0308 l’ha presa oggi. Aperta
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 88/100
Diaoul/subliminal#1405 ·