-
Notifications
You must be signed in to change notification settings - Fork 3.1k
fix: ensure LLM callbacks share the same OTel span context #4854
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
brucearctor
wants to merge
1
commit into
google:main
Choose a base branch
from
brucearctor:fix/otel-span-id-mismatch-4851
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.
+265
−26
Open
Changes from all commits
Commits
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
226 changes: 226 additions & 0 deletions
226
tests/unittests/flows/llm_flows/test_llm_callback_span_consistency.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,226 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """Tests that LLM callbacks share the same OTel span context (issue #4851). | ||
|
|
||
| When OpenTelemetry tracing is enabled, before_model_callback, | ||
| after_model_callback, and on_model_error_callback must all execute within | ||
| the same call_llm span so that plugins (e.g. BigQueryAgentAnalyticsPlugin) | ||
| see a consistent span_id for LLM_REQUEST and LLM_RESPONSE events. | ||
| """ | ||
|
|
||
| from typing import Optional | ||
| from unittest import mock | ||
|
|
||
| from google.adk.agents.callback_context import CallbackContext | ||
| from google.adk.agents.llm_agent import Agent | ||
| from google.adk.flows.llm_flows import base_llm_flow | ||
| from google.adk.models.llm_request import LlmRequest | ||
| from google.adk.models.llm_response import LlmResponse | ||
| from google.adk.plugins.base_plugin import BasePlugin | ||
| from google.adk.telemetry import tracing as adk_tracing | ||
| from google.genai import types | ||
| from opentelemetry import trace | ||
| from opentelemetry.sdk.trace import TracerProvider | ||
| import pytest | ||
|
|
||
| from ... import testing_utils | ||
|
|
||
|
|
||
| def _make_real_tracer(): | ||
| """Create a real tracer that produces valid span IDs.""" | ||
| provider = TracerProvider() | ||
| return provider.get_tracer('test_tracer') | ||
|
|
||
|
|
||
| class SpanCapturingPlugin(BasePlugin): | ||
| """Plugin that captures the current span ID in each model callback.""" | ||
|
|
||
| def __init__(self): | ||
| super().__init__(name='span_capturing_plugin') | ||
| self.before_model_span_id: Optional[int] = None | ||
| self.after_model_span_id: Optional[int] = None | ||
| self.on_model_error_span_id: Optional[int] = None | ||
|
|
||
| async def before_model_callback( | ||
| self, | ||
| *, | ||
| callback_context: CallbackContext, | ||
| llm_request: LlmRequest, | ||
| ) -> Optional[LlmResponse]: | ||
| span = trace.get_current_span() | ||
| ctx = span.get_span_context() | ||
| if ctx and ctx.span_id: | ||
| self.before_model_span_id = ctx.span_id | ||
| return None | ||
|
|
||
| async def after_model_callback( | ||
| self, | ||
| *, | ||
| callback_context: CallbackContext, | ||
| llm_response: LlmResponse, | ||
| ) -> Optional[LlmResponse]: | ||
| span = trace.get_current_span() | ||
| ctx = span.get_span_context() | ||
| if ctx and ctx.span_id: | ||
| self.after_model_span_id = ctx.span_id | ||
| return None | ||
|
|
||
| async def on_model_error_callback( | ||
| self, | ||
| *, | ||
| callback_context: CallbackContext, | ||
| llm_request: LlmRequest, | ||
| error: Exception, | ||
| ) -> Optional[LlmResponse]: | ||
| span = trace.get_current_span() | ||
| ctx = span.get_span_context() | ||
| if ctx and ctx.span_id: | ||
| self.on_model_error_span_id = ctx.span_id | ||
| return LlmResponse( | ||
| content=testing_utils.ModelContent( | ||
| [types.Part.from_text(text='error handled')] | ||
| ) | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_before_and_after_model_callbacks_share_span_id(): | ||
| """Verify before_model_callback and after_model_callback share the same span. | ||
|
|
||
| This is the core regression test for issue #4851. Before the fix, | ||
| before_model_callback ran outside the call_llm span, causing a span_id | ||
| mismatch between LLM_REQUEST and LLM_RESPONSE events. | ||
| """ | ||
| plugin = SpanCapturingPlugin() | ||
| real_tracer = _make_real_tracer() | ||
|
|
||
| mock_model = testing_utils.MockModel.create(responses=['model_response']) | ||
| agent = Agent( | ||
| name='test_agent', | ||
| model=mock_model, | ||
| ) | ||
|
|
||
| with mock.patch.object(base_llm_flow, 'tracer', real_tracer), \ | ||
| mock.patch.object(adk_tracing, 'tracer', real_tracer): | ||
| runner = testing_utils.TestInMemoryRunner(agent, plugins=[plugin]) | ||
| events = await runner.run_async_with_new_session('test') | ||
|
|
||
| # Both callbacks should have captured a span ID | ||
| assert plugin.before_model_span_id is not None, ( | ||
| 'before_model_callback did not capture a span ID' | ||
| ) | ||
| assert plugin.after_model_span_id is not None, ( | ||
| 'after_model_callback did not capture a span ID' | ||
| ) | ||
|
|
||
| # The span IDs must match — this is the core assertion for issue #4851 | ||
| assert plugin.before_model_span_id == plugin.after_model_span_id, ( | ||
| f'Span ID mismatch: before_model_callback span_id=' | ||
| f'{plugin.before_model_span_id:#018x}, ' | ||
| f'after_model_callback span_id={plugin.after_model_span_id:#018x}. ' | ||
| f'Both callbacks must run inside the same call_llm span.' | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_before_and_on_error_model_callbacks_share_span_id(): | ||
| """Verify before_model_callback and on_model_error_callback share span. | ||
|
|
||
| When the model raises an error, on_model_error_callback should see the | ||
| same span as before_model_callback. | ||
| """ | ||
| plugin = SpanCapturingPlugin() | ||
| real_tracer = _make_real_tracer() | ||
|
|
||
| mock_model = testing_utils.MockModel.create( | ||
| responses=[], error=SystemError('model error') | ||
| ) | ||
| agent = Agent( | ||
| name='test_agent', | ||
| model=mock_model, | ||
| ) | ||
|
|
||
| with mock.patch.object(base_llm_flow, 'tracer', real_tracer), \ | ||
| mock.patch.object(adk_tracing, 'tracer', real_tracer): | ||
| runner = testing_utils.TestInMemoryRunner(agent, plugins=[plugin]) | ||
| events = await runner.run_async_with_new_session('test') | ||
|
|
||
| # Both callbacks should have captured a span ID | ||
| assert plugin.before_model_span_id is not None, ( | ||
| 'before_model_callback did not capture a span ID' | ||
| ) | ||
| assert plugin.on_model_error_span_id is not None, ( | ||
| 'on_model_error_callback did not capture a span ID' | ||
| ) | ||
|
|
||
| # The span IDs must match | ||
| assert plugin.before_model_span_id == plugin.on_model_error_span_id, ( | ||
| f'Span ID mismatch: before_model_callback span_id=' | ||
| f'{plugin.before_model_span_id:#018x}, ' | ||
| f'on_model_error_callback span_id=' | ||
| f'{plugin.on_model_error_span_id:#018x}. ' | ||
| f'Both callbacks must run inside the same call_llm span.' | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_before_model_callback_short_circuit_has_span(): | ||
| """Verify before_model_callback has a valid span when short-circuiting.""" | ||
|
|
||
| class ShortCircuitPlugin(BasePlugin): | ||
|
|
||
| def __init__(self): | ||
| super().__init__(name='short_circuit_plugin') | ||
| self.span_id: Optional[int] = None | ||
|
|
||
| async def before_model_callback( | ||
| self, | ||
| *, | ||
| callback_context: CallbackContext, | ||
| llm_request: LlmRequest, | ||
| ) -> Optional[LlmResponse]: | ||
| span = trace.get_current_span() | ||
| ctx = span.get_span_context() | ||
| if ctx and ctx.span_id: | ||
| self.span_id = ctx.span_id | ||
| return LlmResponse( | ||
| content=testing_utils.ModelContent( | ||
| [types.Part.from_text(text='short-circuited')] | ||
| ) | ||
| ) | ||
|
|
||
| plugin = ShortCircuitPlugin() | ||
| real_tracer = _make_real_tracer() | ||
|
|
||
| mock_model = testing_utils.MockModel.create(responses=['model_response']) | ||
| agent = Agent( | ||
| name='test_agent', | ||
| model=mock_model, | ||
| ) | ||
|
|
||
| with mock.patch.object(base_llm_flow, 'tracer', real_tracer), \ | ||
| mock.patch.object(adk_tracing, 'tracer', real_tracer): | ||
| runner = testing_utils.TestInMemoryRunner(agent, plugins=[plugin]) | ||
| events = await runner.run_async_with_new_session('test') | ||
|
|
||
| # The callback should have a valid (non-zero) span ID from the call_llm span | ||
| assert plugin.span_id is not None and plugin.span_id != 0, ( | ||
| 'before_model_callback should have a valid span ID even when ' | ||
| 'short-circuiting the LLM call' | ||
| ) | ||
|
|
||
| # Verify the short-circuit response was received | ||
| simplified = testing_utils.simplify_events(events) | ||
| assert any('short-circuited' in str(e) for e in simplified) |
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.
This block of code for handling the
after_model_callbackis duplicated in theelsebranch on lines 1192-1196. To improve maintainability and avoid repeating code (DRY principle), consider extracting this logic into a local helper coroutine within the_call_llm_with_tracingfunction.For example:
You could then replace both duplicated blocks with a single call:
llm_response = await _apply_after_model_callback(llm_response)