openllmetry icon indicating copy to clipboard operation
openllmetry copied to clipboard

🐛 Bug Report: Google GenAI instrumentation: generate_content_stream spans are never ended on early exit (break, close(), abandoned stream)

Open armanunix opened this issue 2 months ago • 1 comments

Which component is this bug for?

Google Generative AI Instrumentation

📜 Description

For models.generate_content_stream, the span is only ended when the stream is read to the end. If the application stops early (break out of the loop, close() the stream, or drops it), the span is never ended, even after garbage collection, so it is never exported.

Cause: _build_from_streaming_response / _abuild_from_streaming_response (__init__.py) are generators that call span.end() only after the for item in response loop completes. There is no try/finally, so when the application exits early, Python raises GeneratorExit at the yield and the code after the loop, including span.end(), never runs.

Same class of bug as #4536 (Anthropic) and #4532 (OpenAI close()/aclose()).

👟 Reproduction steps

Self-contained, uses httpx.MockTransport (no API key or network); the mock streams three chunks.

import gc, json, logging
logging.disable(logging.WARNING)

import httpx
from google import genai
from google.genai import types
from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
from opentelemetry.instrumentation.google_generativeai import GoogleGenerativeAiInstrumentor

PIECES = ["one ", "two ", "three"]
def handler(request):
    body = "".join("data: " + json.dumps({"candidates": [{"content": {"role": "model", "parts": [{"text": t}]},
                                                          **({"finishReason": "STOP"} if i == 2 else {})}]}) + "\n\n"
                   for i, t in enumerate(PIECES))
    return httpx.Response(200, text=body, headers={"content-type": "text/event-stream"})
client = genai.Client(api_key="x", http_options=types.HttpOptions(
    base_url="http://mock", httpx_client=httpx.Client(transport=httpx.MockTransport(handler))))

class Open(SpanProcessor):
    def __init__(self): self.open = 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)
rec = Open()
provider = TracerProvider()
provider.add_span_processor(rec)
GoogleGenerativeAiInstrumentor().instrument(tracer_provider=provider)

def full():
    for _ in client.models.generate_content_stream(model="m", contents="hi"): pass
def brk():
    for _ in client.models.generate_content_stream(model="m", contents="hi"): break
def close_after_1():
    s = client.models.generate_content_stream(model="m", contents="hi"); next(s); s.close()
def drop_after_1():
    s = client.models.generate_content_stream(model="m", contents="hi"); next(s); del s

for name, fn in [("read all chunks", full), ("break after 1st chunk", brk),
                 ("close() after 1st chunk", close_after_1), ("drop after 1st chunk", drop_after_1)]:
    rec.open.clear()
    fn(); gc.collect()
    print(f"  {name:28s} spans still open after gc: {len(rec.open)}")

Output:

google-genai 2.28.0 | opentelemetry-instrumentation-google-generativeai 0.62.4
  read all chunks              spans still open after gc: 0
  break after 1st chunk        spans still open after gc: 1
  close() after 1st chunk      spans still open after gc: 1
  drop after 1st chunk         spans still open after gc: 1

👍 Expected behavior

The span ends (with the output received so far) when the application breaks out of the loop, closes the stream, or the stream is garbage collected: 0 spans open in every case.

👎 Actual Behavior with Screenshots

The span stays open forever after break, close() or dropping the stream, so it is never exported. Only a fully consumed stream ends its span.

🤖 Python Version

3.12

📃 Provide any additional context for the Bug.

opentelemetry-instrumentation-google-generativeai 0.62.4, google-genai 2.28.0, Linux. Possible fix: move the attribute recording and span.end() into a try/finally around the loop in _build_from_streaming_response and _abuild_from_streaming_response (or catch GeneratorExit), so early exit and garbage collection end the span.

👀 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!

armanunix avatar Oct 04 '26 18:10 armanunix

I can reproduce this on current main and I have a fix ready — the stream builders are plain generators that only call span.end() after the for loop completes, so GeneratorExit from break/close()/GC skips it.

Approach: wrap the chunk loop in try/finally in both _build_from_streaming_response and _abuild_from_streaming_response, moving the attribute recording + span.end() into the finally so early exit ends the span with the partial output received so far. Full-consumption behavior is unchanged (same attributes, same order). Small, additive, no public-API change. PR incoming shortly.

rupak-eng avatar Oct 06 '26 04:10 rupak-eng