diff --git a/src/google/adk/telemetry/_experimental_semconv.py b/src/google/adk/telemetry/_experimental_semconv.py index 55388441365..acddc779289 100644 --- a/src/google/adk/telemetry/_experimental_semconv.py +++ b/src/google/adk/telemetry/_experimental_semconv.py @@ -678,7 +678,7 @@ def set_operation_details_common_attributes( log_only_attributes: Mapping[str, AnyValue] | None = None, ) -> None: operation_details_common_attributes.update(attributes) - if log_only_attributes and telemetry_config.should_add_content_to_logs: + if log_only_attributes and telemetry_config.should_add_user_id_to_logs: operation_details_common_attributes.update(log_only_attributes) diff --git a/src/google/adk/telemetry/context.py b/src/google/adk/telemetry/context.py index 13bdb93d340..7f730ebfbf4 100644 --- a/src/google/adk/telemetry/context.py +++ b/src/google/adk/telemetry/context.py @@ -62,6 +62,9 @@ # Names the experimental telemetry features to enable. _ADK_EXPERIMENTAL_TELEMETRY_FEATURES = 'ADK_EXPERIMENTAL_TELEMETRY_FEATURES' +# Controls where user.id is stored (NO_CONTENT|EVENT_ONLY|SPAN_ONLY|SPAN_AND_EVENT). +ADK_STORE_USER_ID = 'ADK_STORE_USER_ID' + # Token in OTEL_SEMCONV_STABILITY_OPT_IN that selects experimental GenAI semconv. _GENAI_EXPERIMENTAL_OPT_IN = 'gen_ai_latest_experimental' @@ -189,6 +192,25 @@ def _read_ignore_per_request() -> bool: return lock in _TRUTHY_ENV_VALUES +def _read_store_user_id() -> ContentCapturingMode | None: + """Reads ``ADK_STORE_USER_ID`` (defaults to ``None``, unset).""" + stripped = os.getenv(ADK_STORE_USER_ID, '').strip() + if not stripped: + return None + try: + return ContentCapturingMode(stripped.upper()) + except ValueError: + cache_key = f'{ADK_STORE_USER_ID}:{stripped}' + if cache_key not in _warnings_cache: + _warnings_cache.append(cache_key) + logger.warning( + 'Ignoring unrecognized %s value: %s', + ADK_STORE_USER_ID, + stripped, + ) + return None + + class TelemetryConfig(BaseModel): """Per-request OpenTelemetry configuration. @@ -241,6 +263,7 @@ class TelemetryConfig(BaseModel): _env_enabled_experimental_features: frozenset[str] = PrivateAttr() _env_ignore_per_request: bool = PrivateAttr() _env_schema_version: int = PrivateAttr() + _env_store_user_id: ContentCapturingMode | None = PrivateAttr() def model_post_init(self, context: Any, /) -> None: """Resolves the env-backed answers now, rather than on first read.""" @@ -254,6 +277,7 @@ def model_post_init(self, context: Any, /) -> None: ) self._env_ignore_per_request = _read_ignore_per_request() self._env_schema_version = resolve_schema_version() + self._env_store_user_id = _read_store_user_id() def __eq__(self, other: object) -> bool: """Compares the fields, ignoring the env fallbacks cached beside them.""" @@ -332,6 +356,32 @@ def should_add_content_to_logs(self) -> bool: ContentCapturingMode.SPAN_AND_EVENT, ) + @property + def store_user_id_mode(self) -> ContentCapturingMode | None: + """The configured ``ADK_STORE_USER_ID`` mode, or ``None`` if unset.""" + return self._env_store_user_id + + @property + def should_add_user_id_to_spans(self) -> bool: + """Whether ``user.id`` goes on inference spans.""" + if self._env_store_user_id is None: + return False + return _is_span_bearing(self._env_store_user_id) + + @property + def should_add_user_id_to_logs(self) -> bool: + """Whether ``user.id`` goes on emitted inference log records. + + Uses ``ADK_STORE_USER_ID`` when set; otherwise falls back to + :attr:`should_add_content_to_logs`. + """ + if self._env_store_user_id is not None: + return self._env_store_user_id in ( + ContentCapturingMode.EVENT_ONLY, + ContentCapturingMode.SPAN_AND_EVENT, + ) + return self.should_add_content_to_logs + @property def should_add_content_to_experimental_spans(self) -> bool: """Whether content goes on semconv spans (inference, and v2 tool spans). diff --git a/src/google/adk/telemetry/tracing.py b/src/google/adk/telemetry/tracing.py index 85e27cd0e22..cc181d8294e 100644 --- a/src/google/adk/telemetry/tracing.py +++ b/src/google/adk/telemetry/tracing.py @@ -113,6 +113,7 @@ from ._stable_semconv import user_message_body from ._token_usage import TokenUsage from .context import _TRUTHY_ENV_VALUES +from .context import ContentCapturingMode from .context import TelemetryConfig # Use the import symbols once the minimum OpenTelemetry SDK version is updated to 1.40.0 @@ -179,6 +180,8 @@ # Silence unused warnings, but keep the public interface the same. _ = OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT +_warned_missing_event_only_key = False + # Needed to avoid circular imports if TYPE_CHECKING: from opentelemetry.util.types import AnyValue @@ -1095,6 +1098,48 @@ def _telemetry_config_from_invocation_context( return TelemetryConfig() +def _build_inference_attributes( + agent: BaseAgent | BaseNode, + invocation_context: InvocationContext, + model_response_event: Event, + telemetry_config: TelemetryConfig, +) -> tuple[ + dict[str, AttributeValue], + dict[str, AttributeValue], + dict[str, AttributeValue], + dict[str, AttributeValue], +]: + """Builds common, span, log-only, and delegated log-only inference attrs.""" + common_attributes: dict[str, AttributeValue] = { + GEN_AI_AGENT_NAME: agent.name, + GEN_AI_CONVERSATION_ID: invocation_context.session.id, + "gcp.vertex.agent.event_id": model_response_event.id, + "gcp.vertex.agent.invocation_id": invocation_context.invocation_id, + } + user_id = invocation_context.session.user_id + span_attributes = dict(common_attributes) + log_only_common_attributes: dict[str, AttributeValue] = {} + if user_id is not None: + log_only_common_attributes[USER_ID] = user_id + if telemetry_config.should_add_user_id_to_spans: + span_attributes[USER_ID] = user_id + + if ( + telemetry_config.store_user_id_mode is ContentCapturingMode.NO_CONTENT + or telemetry_config.should_add_user_id_to_spans + ): + delegated_log_only_attributes: dict[str, AttributeValue] = {} + else: + delegated_log_only_attributes = dict(log_only_common_attributes) + + return ( + common_attributes, + span_attributes, + log_only_common_attributes, + delegated_log_only_attributes, + ) + + @deprecated("Replaced by use_inference_span to support experimental semconv.") @contextmanager def use_generate_content_span( @@ -1115,27 +1160,27 @@ def use_generate_content_span( agent = invocation_context.agent if agent is None: raise ValueError("The invocation context must have an agent.") - common_attributes = { - GEN_AI_AGENT_NAME: agent.name, - GEN_AI_CONVERSATION_ID: invocation_context.session.id, - "gcp.vertex.agent.event_id": model_response_event.id, - "gcp.vertex.agent.invocation_id": invocation_context.invocation_id, - } - log_only_common_attributes = {} - if invocation_context.session.user_id is not None: - log_only_common_attributes[USER_ID] = invocation_context.session.user_id + ( + _, + span_attributes, + log_only_common_attributes, + delegated_log_only_attributes, + ) = _build_inference_attributes( + agent, invocation_context, model_response_event, telemetry_config + ) if _should_emit_native_telemetry(agent, telemetry_config): with _use_native_generate_content_span_stable_semconv( llm_request=llm_request, - common_attributes=common_attributes, + common_attributes=span_attributes, log_only_common_attributes=log_only_common_attributes, telemetry_config=telemetry_config, ) as span: yield span.span else: with _use_extra_generate_content_attributes( - common_attributes, - log_only_extra_attributes=log_only_common_attributes, + span_attributes, + log_only_extra_attributes=delegated_log_only_attributes, + telemetry_config=telemetry_config, ): yield None @@ -1159,15 +1204,14 @@ async def use_inference_span( agent = invocation_context.agent if agent is None: raise ValueError("The invocation context must have an agent.") - common_attributes = { - GEN_AI_AGENT_NAME: agent.name, - GEN_AI_CONVERSATION_ID: invocation_context.session.id, - "gcp.vertex.agent.event_id": model_response_event.id, - "gcp.vertex.agent.invocation_id": invocation_context.invocation_id, - } - log_only_common_attributes = {} - if invocation_context.session.user_id is not None: - log_only_common_attributes[USER_ID] = invocation_context.session.user_id + ( + common_attributes, + span_attributes, + log_only_common_attributes, + delegated_log_only_attributes, + ) = _build_inference_attributes( + agent, invocation_context, model_response_event, telemetry_config + ) if _should_emit_native_telemetry(agent, telemetry_config): if ( telemetry_config.should_use_experimental_genai_semconv @@ -1176,14 +1220,14 @@ async def use_inference_span( # Semconv >= 1.37 replaces `gen_ai.system`; both are kept for consumers. # Schema v1 keeps `gen_ai.system` only, as it did before the provider # name existed. - common_attributes[GEN_AI_PROVIDER_NAME] = _resolve_gen_ai_provider_name( - llm_request.model - ) + provider_name = _resolve_gen_ai_provider_name(llm_request.model) + common_attributes[GEN_AI_PROVIDER_NAME] = provider_name + span_attributes[GEN_AI_PROVIDER_NAME] = provider_name with ExitStack() as stack: gc_span = stack.enter_context( _use_native_generate_content_span( llm_request=llm_request, - common_attributes=common_attributes, + common_attributes=span_attributes, log_only_common_attributes=log_only_common_attributes, telemetry_config=telemetry_config, ) @@ -1213,8 +1257,9 @@ def _log_completion_details() -> None: yield gc_span else: with _use_extra_generate_content_attributes( - common_attributes, - log_only_extra_attributes=log_only_common_attributes, + span_attributes, + log_only_extra_attributes=delegated_log_only_attributes, + telemetry_config=telemetry_config, ): yield None @@ -1236,7 +1281,9 @@ def _should_emit_native_telemetry( def _use_extra_generate_content_attributes( extra_attributes: Mapping[str, AttributeValue], log_only_extra_attributes: Mapping[str, AttributeValue] | None = None, + telemetry_config: TelemetryConfig | None = None, ) -> Iterator[None]: + global _warned_missing_event_only_key try: from opentelemetry.instrumentation.google_genai import GENERATE_CONTENT_EXTRA_ATTRIBUTES_CONTEXT_KEY except (ImportError, AttributeError): @@ -1250,10 +1297,22 @@ def _use_extra_generate_content_attributes( return + effective_config = telemetry_config or TelemetryConfig() + resolved_extra_attributes: dict[str, AttributeValue] = dict(extra_attributes) + remaining_log_only = ( + dict(log_only_extra_attributes) if log_only_extra_attributes else {} + ) + if remaining_log_only: + if effective_config.should_add_user_id_to_spans: + resolved_extra_attributes.update(remaining_log_only) + remaining_log_only = {} + elif effective_config.store_user_id_mode is ContentCapturingMode.NO_CONTENT: + remaining_log_only = {} + ctx = otel_context.set_value( - GENERATE_CONTENT_EXTRA_ATTRIBUTES_CONTEXT_KEY, extra_attributes + GENERATE_CONTENT_EXTRA_ATTRIBUTES_CONTEXT_KEY, resolved_extra_attributes ) - if log_only_extra_attributes: + if remaining_log_only: try: from opentelemetry.instrumentation import google_genai @@ -1264,11 +1323,20 @@ def _use_extra_generate_content_attributes( ) ctx = otel_context.set_value( event_only_key, - log_only_extra_attributes, + remaining_log_only, context=ctx, ) except (ImportError, AttributeError): - pass + if not _warned_missing_event_only_key: + _warned_missing_event_only_key = True + logger.warning( + "opentelemetry-instrumentation-google-genai does not export" + " GENERATE_CONTENT_EVENT_ONLY_EXTRA_ATTRIBUTES_CONTEXT_KEY; %s" + " will not be attached to instrumented telemetry. Set" + " ADK_STORE_USER_ID=SPAN_ONLY or SPAN_AND_EVENT to attach it" + " via GENERATE_CONTENT_EXTRA_ATTRIBUTES_CONTEXT_KEY.", + ", ".join(sorted(remaining_log_only)), + ) tok = otel_context.attach(ctx) try: @@ -1325,7 +1393,7 @@ def _use_native_generate_content_span_stable_semconv( GEN_AI_SYSTEM: system_name } if ( - telemetry_config.should_add_content_to_logs + telemetry_config.should_add_user_id_to_logs and log_only_common_attributes ): user_id = log_only_common_attributes.get(USER_ID) diff --git a/tests/unittests/telemetry/test_genai_instrumentor_bypass.py b/tests/unittests/telemetry/test_genai_instrumentor_bypass.py index 727ec891daa..6109086ca1d 100644 --- a/tests/unittests/telemetry/test_genai_instrumentor_bypass.py +++ b/tests/unittests/telemetry/test_genai_instrumentor_bypass.py @@ -427,3 +427,44 @@ async def sdk_stub_with_usage( for point in metric.data.data_points ] assert (point.count, point.sum) == (1, 10) + + +@pytest.mark.parametrize( + "store_user_id_mode,expect_user_id_on_span", + [ + (None, False), + ("NO_CONTENT", False), + ("EVENT_ONLY", False), + ("SPAN_ONLY", True), + ("SPAN_AND_EVENT", True), + ], +) +@pytest.mark.asyncio +async def test_instrumented_span_records_user_id_when_opted_in( + monkeypatch: pytest.MonkeyPatch, + provider: TracerProvider, + store_user_id_mode: str | None, + expect_user_id_on_span: bool, +) -> None: + """``ADK_STORE_USER_ID`` controls ``user.id`` on the instrumentor's span.""" + monkeypatch.setenv("ADK_TELEMETRY_SCHEMA_VERSION_OPT_IN", "2") + monkeypatch.setenv("OTEL_SEMCONV_STABILITY_OPT_IN", _EXPERIMENTAL) + if store_user_id_mode is None: + monkeypatch.delenv("ADK_STORE_USER_ID", raising=False) + else: + monkeypatch.setenv("ADK_STORE_USER_ID", store_user_id_mode) + + with _instrumented(monkeypatch, provider) as exporter: + await _run_inference(TelemetryConfig()) + + gen_ai_spans = [ + span + for span in exporter.get_finished_spans() + if span.name.startswith("generate_content") + ] + assert len(gen_ai_spans) == 1 + attrs = gen_ai_spans[0].attributes or {} + if expect_user_id_on_span: + assert attrs.get("user.id") == "test_user" + else: + assert "user.id" not in attrs diff --git a/tests/unittests/telemetry/test_spans.py b/tests/unittests/telemetry/test_spans.py index 8ae2694f183..a969edbf84a 100644 --- a/tests/unittests/telemetry/test_spans.py +++ b/tests/unittests/telemetry/test_spans.py @@ -3459,6 +3459,192 @@ def test_use_extra_generate_content_attributes_older_version(monkeypatch): pytest.fail(f'Graceful degradation failed: {e}') +def test_use_extra_generate_content_attributes_missing_key_warns_once( + monkeypatch, caplog +): + """Missing event-only context key logs a one-time warning when dropping.""" + from opentelemetry.instrumentation import google_genai + + monkeypatch.delenv('ADK_STORE_USER_ID', raising=False) + monkeypatch.setattr( + 'google.adk.telemetry.tracing._warned_missing_event_only_key', False + ) + if hasattr( + google_genai, 'GENERATE_CONTENT_EVENT_ONLY_EXTRA_ATTRIBUTES_CONTEXT_KEY' + ): + monkeypatch.delattr( + google_genai, 'GENERATE_CONTENT_EVENT_ONLY_EXTRA_ATTRIBUTES_CONTEXT_KEY' + ) + + with caplog.at_level('WARNING', logger='google_adk'): + with mock.patch('opentelemetry.context.set_value') as mock_set_value: + with _use_extra_generate_content_attributes( + extra_attributes={'span.attr': 'value'}, + log_only_extra_attributes={USER_ID: 'user_123'}, + ): + pass + with _use_extra_generate_content_attributes( + extra_attributes={'span.attr': 'value'}, + log_only_extra_attributes={USER_ID: 'user_123'}, + ): + pass + + mock_set_value.assert_called_with( + google_genai.GENERATE_CONTENT_EXTRA_ATTRIBUTES_CONTEXT_KEY, + {'span.attr': 'value'}, + ) + assert len(caplog.records) == 1 + assert USER_ID in caplog.records[0].getMessage() + + +@pytest.mark.parametrize('mode', ['SPAN_ONLY', 'SPAN_AND_EVENT']) +def test_use_extra_generate_content_attributes_span_opt_in_forwards_user_id( + monkeypatch, caplog, mode +): + """``ADK_STORE_USER_ID=SPAN_ONLY|SPAN_AND_EVENT`` merges log-only attrs onto span extras.""" + from opentelemetry.instrumentation import google_genai + + monkeypatch.setenv('ADK_STORE_USER_ID', mode) + monkeypatch.setattr( + 'google.adk.telemetry.tracing._warned_missing_event_only_key', False + ) + if hasattr( + google_genai, 'GENERATE_CONTENT_EVENT_ONLY_EXTRA_ATTRIBUTES_CONTEXT_KEY' + ): + monkeypatch.delattr( + google_genai, 'GENERATE_CONTENT_EVENT_ONLY_EXTRA_ATTRIBUTES_CONTEXT_KEY' + ) + + with caplog.at_level('WARNING', logger='google_adk'): + with mock.patch('opentelemetry.context.set_value') as mock_set_value: + with _use_extra_generate_content_attributes( + extra_attributes={'span.attr': 'value'}, + log_only_extra_attributes={USER_ID: 'user_123'}, + ): + pass + + mock_set_value.assert_called_once_with( + google_genai.GENERATE_CONTENT_EXTRA_ATTRIBUTES_CONTEXT_KEY, + {'span.attr': 'value', USER_ID: 'user_123'}, + ) + assert not caplog.records + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + 'mode,expect_in_extra,expect_in_log_only', + [ + (None, False, True), + ('NO_CONTENT', False, False), + ('EVENT_ONLY', False, True), + ('SPAN_ONLY', True, False), + ('SPAN_AND_EVENT', True, False), + ], +) +@mock.patch( + 'google.adk.telemetry.tracing._use_extra_generate_content_attributes' +) +async def test_use_inference_span_delegation_respects_adk_store_user_id( + mock_use_extra, + monkeypatch, + mode, + expect_in_extra, + expect_in_log_only, +): + """Delegated Gemini inference obeys ``ADK_STORE_USER_ID``.""" + monkeypatch.setattr( + 'google.adk.telemetry._genai_instrumentor.is_instrumented', + lambda: True, + ) + monkeypatch.setenv( + 'OTEL_SEMCONV_STABILITY_OPT_IN', 'gen_ai_latest_experimental' + ) + if mode is None: + monkeypatch.delenv('ADK_STORE_USER_ID', raising=False) + else: + monkeypatch.setenv('ADK_STORE_USER_ID', mode) + + agent = LlmAgent(name='test_agent', model='gemini-1.5-pro') + invocation_context = await _create_invocation_context(agent) + llm_request = LlmRequest( + model='gemini-1.5-pro', + contents=[types.Content(role='user', parts=[types.Part(text='Hello')])], + ) + model_response_event = mock.MagicMock() + model_response_event.id = 'event-123' + + async with use_inference_span( + llm_request, invocation_context, model_response_event + ): + pass + + mock_use_extra.assert_called_once() + extra_attrs = mock_use_extra.call_args.args[0] + log_only_attrs = mock_use_extra.call_args.kwargs['log_only_extra_attributes'] + assert (USER_ID in extra_attrs) is expect_in_extra + assert (USER_ID in log_only_attrs) is expect_in_log_only + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + 'mode,expect_on_span,expect_on_log', + [ + ('NO_CONTENT', False, False), + ('EVENT_ONLY', False, True), + ('SPAN_ONLY', True, False), + ('SPAN_AND_EVENT', True, True), + ], +) +@mock.patch('google.adk.telemetry.tracing.otel_logger') +@mock.patch('google.adk.telemetry.tracing.tracer') +async def test_use_inference_span_native_respects_adk_store_user_id( + mock_tracer, + mock_otel_logger, + monkeypatch, + mode, + expect_on_span, + expect_on_log, +): + """Native inference spans and operation-details logs obey ``ADK_STORE_USER_ID``.""" + monkeypatch.setenv('ADK_TELEMETRY_SCHEMA_VERSION_OPT_IN', '2') + monkeypatch.setenv( + 'OTEL_SEMCONV_STABILITY_OPT_IN', 'gen_ai_latest_experimental' + ) + monkeypatch.setenv('ADK_STORE_USER_ID', mode) + monkeypatch.delenv( + 'OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT', raising=False + ) + + mock_span = mock.MagicMock() + mock_tracer.start_as_current_span.return_value.__enter__.return_value = ( + mock_span + ) + + agent = LlmAgent(name='test_agent', model='some-model') + invocation_context = await _create_invocation_context(agent) + llm_request = LlmRequest( + model='some-model', + contents=[types.Content(role='user', parts=[types.Part(text='Hello')])], + ) + model_response_event = mock.MagicMock() + model_response_event.id = 'event-123' + + async with use_inference_span( + llm_request, invocation_context, model_response_event + ): + pass + + span_set_attrs = {} + for call in mock_span.set_attributes.call_args_list: + span_set_attrs.update(call.args[0]) + for call in mock_span.set_attribute.call_args_list: + span_set_attrs[call.args[0]] = call.args[1] + + assert (USER_ID in span_set_attrs) is expect_on_span + log_record = mock_otel_logger.emit.call_args.args[0] + assert (USER_ID in (log_record.attributes or {})) is expect_on_log + + # --------------------------------------------------------------------------- # Tests for _detect_error_in_response # --------------------------------------------------------------------------- diff --git a/tests/unittests/telemetry/test_telemetry_context.py b/tests/unittests/telemetry/test_telemetry_context.py index 9b8aaf704ce..d7b65d92d31 100644 --- a/tests/unittests/telemetry/test_telemetry_context.py +++ b/tests/unittests/telemetry/test_telemetry_context.py @@ -53,6 +53,7 @@ _ENV_ADK_EXPERIMENTAL_FEATURES = 'ADK_EXPERIMENTAL_TELEMETRY_FEATURES' _ENV_SCHEMA_VERSION = 'ADK_TELEMETRY_SCHEMA_VERSION_OPT_IN' +_ENV_STORE_USER_ID = 'ADK_STORE_USER_ID' _ALL_TELEMETRY_ENV_VARS = ( _ENV_EXPERIMENTAL, @@ -62,6 +63,7 @@ _ENV_ADK_EXPERIMENTAL_TELEMETRY, _ENV_ADK_EXPERIMENTAL_FEATURES, _ENV_SCHEMA_VERSION, + _ENV_STORE_USER_ID, ) @@ -1644,3 +1646,57 @@ async def test_runner_invocation_per_request_opt_out_beats_env_opt_in( 'the scope read ADK_EXPERIMENTAL_TELEMETRY instead of the per-request' f' opt-out. recorded={sorted(recorded)}' ) + + +@pytest.mark.parametrize( + 'store_user_id_env,capture_env,expect_spans,expect_logs', + [ + (None, None, False, False), + (None, 'EVENT_ONLY', False, True), + (None, 'SPAN_ONLY', False, False), + ('NO_CONTENT', 'SPAN_AND_EVENT', False, False), + ('EVENT_ONLY', None, False, True), + ('SPAN_ONLY', 'EVENT_ONLY', True, False), + ('SPAN_AND_EVENT', None, True, True), + ('span_only', None, True, False), + ], +) +def test_store_user_id_controls_span_and_log_routing( + monkeypatch: pytest.MonkeyPatch, + store_user_id_env: str | None, + capture_env: str | None, + expect_spans: bool, + expect_logs: bool, +): + """``ADK_STORE_USER_ID`` gates ``user.id`` placement independently.""" + _set_env( + monkeypatch, + **{ + _ENV_STORE_USER_ID: store_user_id_env, + _ENV_CAPTURE: capture_env, + }, + ) + cfg = TelemetryConfig() + assert cfg.should_add_user_id_to_spans is expect_spans + assert cfg.should_add_user_id_to_logs is expect_logs + + out = _run_set_common_attrs(cfg) + assert ('gen_ai.user.id' in out) is expect_logs + + +def test_store_user_id_unrecognized_value_warns_once( + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +): + """Invalid ``ADK_STORE_USER_ID`` values warn once and fall back to unset.""" + _set_env(monkeypatch, **{_ENV_STORE_USER_ID: 'invalid_user_mode'}) + with caplog.at_level('WARNING', logger='google_adk'): + cfg1 = TelemetryConfig() + cfg2 = TelemetryConfig() + + assert cfg1.store_user_id_mode is None + assert cfg2.store_user_id_mode is None + assert cfg1.should_add_user_id_to_spans is False + assert [r.getMessage() for r in caplog.records] == [ + 'Ignoring unrecognized ADK_STORE_USER_ID value: invalid_user_mode' + ]