Repository navigation
[google-genai] Restore caller context between stream reads #899
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
JacksonWeber
wants to merge
7
commits into
open-telemetry:main
Choose a base branch
from
JacksonWeber:jacksonweber-next-genai-issue
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
74bea0b
Fix Google GenAI stream execution context
JacksonWeber 9334abd
Name changelog fragment for PR 899
JacksonWeber d6c41f2
Clarify Google GenAI stream test cases and SDK skips
JacksonWeber 41bf6c5
Simplify Google GenAI stream context regression coverage
JacksonWeber e78572a
Suspend invocations in shared stream constructors
JacksonWeber 3dd4685
Merge branch 'main' into jacksonweber-next-genai-issue
DylanRussell 2b53976
Split Google GenAI stream context tests by execution mode
JacksonWeber File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 change: 1 addition & 0 deletions
1
instrumentation/opentelemetry-instrumentation-google-genai/.changelog/899.fixed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Restore caller context between Google GenAI stream reads while preserving invocation context during iteration and cleanup. |
314 changes: 314 additions & 0 deletions
314
instrumentation/opentelemetry-instrumentation-google-genai/tests/test_stream_context.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,314 @@ | ||
| # Copyright The OpenTelemetry Authors | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| from collections.abc import AsyncIterator, Iterator | ||
| from contextlib import nullcontext | ||
| from functools import wraps | ||
|
|
||
| import pytest | ||
| from google.genai import Client | ||
| from google.genai.models import AsyncModels, Models | ||
| from google.genai.types import GenerateContentResponse | ||
|
|
||
| from opentelemetry import context, trace | ||
| from opentelemetry.instrumentation.google_genai import ( | ||
| GoogleGenAiSdkInstrumentor, | ||
| ) | ||
| from opentelemetry.instrumentation.google_genai.interactions import ( | ||
| _HAS_INTERACTIONS, | ||
| AsyncInteractionsResource, | ||
| InteractionsResource, | ||
| ) | ||
| from opentelemetry.sdk._logs import LoggerProvider | ||
| from opentelemetry.sdk.metrics import MeterProvider | ||
| from opentelemetry.sdk.trace import TracerProvider | ||
| from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( | ||
| InMemorySpanExporter, | ||
| ) | ||
| from opentelemetry.semconv._incubating.attributes import gen_ai_attributes | ||
| from opentelemetry.semconv.attributes.error_attributes import ERROR_TYPE | ||
| from opentelemetry.test_util_genai.instrumentor import instrument | ||
| from opentelemetry.trace import Span, StatusCode | ||
|
|
||
| REQUIRES_INTERACTIONS = pytest.mark.skipif( | ||
| not _HAS_INTERACTIONS, | ||
| reason="Interactions are not supported in this version of google-genai", | ||
| ) | ||
|
|
||
|
|
||
| pytestmark = [ | ||
| pytest.mark.parametrize( | ||
| "expected_operation", | ||
| [ | ||
| pytest.param( | ||
| "generate_content", id="models.generate_content_stream" | ||
| ), | ||
| pytest.param( | ||
| "interactions.create", | ||
| id="interactions.create-model", | ||
| marks=REQUIRES_INTERACTIONS, | ||
| ), | ||
| pytest.param( | ||
| "invoke_agent", | ||
| id="interactions.create-agent", | ||
| marks=REQUIRES_INTERACTIONS, | ||
| ), | ||
| pytest.param( | ||
| "fetch_response", | ||
| id="interactions.get", | ||
| marks=REQUIRES_INTERACTIONS, | ||
| ), | ||
| ], | ||
| ), | ||
| pytest.mark.parametrize( | ||
| "ending", ["drain", "caller_error", "stream_error"] | ||
| ), | ||
| ] | ||
|
|
||
|
|
||
| def _assert_finished_spans( | ||
| span_exporter: InMemorySpanExporter, | ||
| sdk_span: Span, | ||
| caller: Span, | ||
| expected_operation: str, | ||
| ending: str, | ||
| ) -> None: | ||
| invocation_span, caller_span = span_exporter.get_finished_spans() | ||
| assert invocation_span.context == sdk_span.get_span_context() | ||
| assert invocation_span.parent == caller.get_span_context() | ||
| assert caller_span.context == caller.get_span_context() | ||
| assert invocation_span.attributes is not None | ||
| assert ( | ||
| invocation_span.attributes[gen_ai_attributes.GEN_AI_OPERATION_NAME] | ||
| == expected_operation | ||
| ) | ||
| failed = ending != "drain" | ||
| assert invocation_span.status.status_code == ( | ||
| StatusCode.ERROR if failed else StatusCode.UNSET | ||
| ) | ||
| if failed: | ||
| assert invocation_span.attributes[ERROR_TYPE] == "ConnectionError" | ||
| else: | ||
| assert ERROR_TYPE not in invocation_span.attributes | ||
|
|
||
|
|
||
| def test_sync_stream_context( | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| tracer_provider: TracerProvider, | ||
| meter_provider: MeterProvider, | ||
| logger_provider: LoggerProvider, | ||
| span_exporter: InMemorySpanExporter, | ||
| expected_operation: str, | ||
| ending: str, | ||
| ) -> None: | ||
| tracer = tracer_provider.get_tracer(__name__) | ||
| sdk_span: Span | None = None | ||
| error = ConnectionError("stream failed") | ||
| chunk = ( | ||
| GenerateContentResponse(response_id="response-id", candidates=[]) | ||
| if expected_operation == "generate_content" | ||
| else {"event_type": "content"} | ||
| ) | ||
|
|
||
| def produce() -> Iterator[object]: | ||
| for _ in range(2): | ||
| assert trace.get_current_span() is sdk_span | ||
| yield chunk | ||
| if ending == "stream_error": | ||
| raise error | ||
|
|
||
| resource_type = ( | ||
| Models | ||
| if expected_operation == "generate_content" | ||
| else InteractionsResource | ||
| ) | ||
| method_name = ( | ||
| "generate_content_stream" | ||
| if expected_operation == "generate_content" | ||
| else "get" | ||
| if expected_operation == "fetch_response" | ||
| else "create" | ||
| ) | ||
| original = getattr(resource_type, method_name) | ||
| source = produce() | ||
|
|
||
| @wraps(original) | ||
| def call(*args: object, **kwargs: object) -> Iterator[object]: | ||
| nonlocal sdk_span | ||
| sdk_span = trace.get_current_span() | ||
| return source | ||
|
|
||
| monkeypatch.setattr(resource_type, method_name, call) | ||
| # The instrumentor sets this independently of the shared content setting. | ||
| monkeypatch.setenv("OTEL_INSTRUMENTATION_GENAI_EMIT_EVENT", "true") | ||
| with ( | ||
| instrument( | ||
| GoogleGenAiSdkInstrumentor(), | ||
| tracer_provider=tracer_provider, | ||
| meter_provider=meter_provider, | ||
| logger_provider=logger_provider, | ||
| content_capture="NO_CONTENT", | ||
| ), | ||
| tracer.start_as_current_span("caller") as caller, | ||
| ): | ||
| client = Client(api_key="test-key") | ||
| before = context.get_current() | ||
| if expected_operation == "generate_content": | ||
| stream = client.models.generate_content_stream( | ||
| model="gemini-2.5-flash", contents="Hello" | ||
| ) | ||
| elif expected_operation == "fetch_response": | ||
| stream = client.interactions.get("response-id", stream=True) | ||
| elif expected_operation == "invoke_agent": | ||
| stream = client.interactions.create( | ||
| agent="test-agent", input="Hello", stream=True | ||
| ) | ||
| else: | ||
| stream = client.interactions.create( | ||
| model="gemini-2.5-flash", input="Hello", stream=True | ||
| ) | ||
| assert sdk_span is not None | ||
| assert sdk_span.is_recording() | ||
| assert context.get_current() is before | ||
| received: list[object] = [] | ||
|
|
||
| with ( | ||
| pytest.raises(ConnectionError) | ||
| if ending != "drain" | ||
| else nullcontext() | ||
| ) as raised: | ||
| with stream: | ||
| for item in stream: | ||
| assert item is chunk | ||
| assert context.get_current() is before | ||
| assert sdk_span.is_recording() | ||
| received.append(item) | ||
| if ending == "caller_error": | ||
| raise error | ||
|
|
||
| if raised is not None: | ||
| assert raised.value is error | ||
| assert len(received) == (2 if ending == "drain" else 1) | ||
| assert context.get_current() is before | ||
| assert not sdk_span.is_recording() | ||
|
|
||
| _assert_finished_spans( | ||
| span_exporter, sdk_span, caller, expected_operation, ending | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_async_stream_context( | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| tracer_provider: TracerProvider, | ||
| meter_provider: MeterProvider, | ||
| logger_provider: LoggerProvider, | ||
| span_exporter: InMemorySpanExporter, | ||
| expected_operation: str, | ||
| ending: str, | ||
| ) -> None: | ||
| tracer = tracer_provider.get_tracer(__name__) | ||
| sdk_span: Span | None = None | ||
| error = ConnectionError("stream failed") | ||
| chunk = ( | ||
| GenerateContentResponse(response_id="response-id", candidates=[]) | ||
| if expected_operation == "generate_content" | ||
| else {"event_type": "content"} | ||
| ) | ||
|
|
||
| async def produce() -> AsyncIterator[object]: | ||
| for _ in range(2): | ||
| assert trace.get_current_span() is sdk_span | ||
| yield chunk | ||
| if ending == "stream_error": | ||
| raise error | ||
|
|
||
| resource_type = ( | ||
| AsyncModels | ||
| if expected_operation == "generate_content" | ||
| else AsyncInteractionsResource | ||
| ) | ||
| method_name = ( | ||
| "generate_content_stream" | ||
| if expected_operation == "generate_content" | ||
| else "get" | ||
| if expected_operation == "fetch_response" | ||
| else "create" | ||
| ) | ||
| original = getattr(resource_type, method_name) | ||
| source = produce() | ||
|
|
||
| @wraps(original) | ||
| async def call(*args: object, **kwargs: object) -> AsyncIterator[object]: | ||
| nonlocal sdk_span | ||
| sdk_span = trace.get_current_span() | ||
| return source | ||
|
|
||
| monkeypatch.setattr(resource_type, method_name, call) | ||
| # The instrumentor sets this independently of the shared content setting. | ||
| monkeypatch.setenv("OTEL_INSTRUMENTATION_GENAI_EMIT_EVENT", "true") | ||
| with ( | ||
| instrument( | ||
| GoogleGenAiSdkInstrumentor(), | ||
| tracer_provider=tracer_provider, | ||
| meter_provider=meter_provider, | ||
| logger_provider=logger_provider, | ||
| content_capture="NO_CONTENT", | ||
| ), | ||
| tracer.start_as_current_span("caller") as caller, | ||
| ): | ||
| client = Client(api_key="test-key") | ||
| before = context.get_current() | ||
| if expected_operation == "generate_content": | ||
| stream = await client.aio.models.generate_content_stream( | ||
| model="gemini-2.5-flash", contents="Hello" | ||
| ) | ||
| elif expected_operation == "fetch_response": | ||
| stream = await client.aio.interactions.get( | ||
| "response-id", stream=True | ||
| ) | ||
| elif expected_operation == "invoke_agent": | ||
| stream = await client.aio.interactions.create( | ||
| agent="test-agent", input="Hello", stream=True | ||
| ) | ||
| else: | ||
| stream = await client.aio.interactions.create( | ||
| model="gemini-2.5-flash", input="Hello", stream=True | ||
| ) | ||
| assert sdk_span is not None | ||
| assert sdk_span.is_recording() | ||
| assert context.get_current() is before | ||
| received: list[object] = [] | ||
|
|
||
| async def consume() -> None: | ||
| try: | ||
| async with stream: | ||
| async for item in stream: | ||
| assert item is chunk | ||
| assert context.get_current() is before | ||
| assert sdk_span.is_recording() | ||
| received.append(item) | ||
| if ending == "caller_error": | ||
| raise error | ||
| finally: | ||
| assert context.get_current() is before | ||
|
|
||
| with ( | ||
| pytest.raises(ConnectionError) | ||
| if ending != "drain" | ||
| else nullcontext() | ||
| ) as raised: | ||
| await asyncio.create_task(consume()) | ||
|
|
||
| if raised is not None: | ||
| assert raised.value is error | ||
| assert len(received) == (2 if ending == "drain" else 1) | ||
| assert context.get_current() is before | ||
| assert not sdk_span.is_recording() | ||
|
|
||
| _assert_finished_spans( | ||
| span_exporter, sdk_span, caller, expected_operation, ending | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Suspend invocations in the shared stream wrapper constructors so caller context is restored between stream reads. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why does simply calling
invocation.suspendin the initializer of these stream wrappers require such a massive test ? Can we have a simpler test or can you explain why this is necessary ?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I’ve trimmed it to context restoration for sync and async calls. Tests should be simpler now, let me know if they look good now
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
its better but i dont love all the branching logic.. maybe split it in 2 1 for sync 1 with async ? I think that'd get rid of a lot of it
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Split it into separate sync and async tests, should remove the branching logic