diff --git a/packages/genkit-otel/README.md b/packages/genkit-otel/README.md index 1d6fe1cb4..2070fac8e 100644 --- a/packages/genkit-otel/README.md +++ b/packages/genkit-otel/README.md @@ -54,6 +54,29 @@ ai = Genkit() When the SDK is not initialized, the provider is effectively a no-op. +### Flushing before exit + +`BatchSpanProcessor` and periodic metric readers buffer exports. A +serverless handler or a short script can return before they're sent. Call +`flush_instrumentations()` before the process freezes. It force-flushes the +global OTel tracer, meter, and logger providers. If a flush fails, it logs a +warning and doesn't raise: + +```python +import asyncio + +from genkit.telemetry import flush_instrumentations + +# 1. Handle the request +response = await ai.generate(prompt='Suggest a dish for a peanut allergy.') + +# 2. Drain buffered spans, metrics, and log events before returning +await asyncio.to_thread(flush_instrumentations) +``` + +If you passed `tracer`, `meter`, or `otel_logger` explicitly, flush the +provider you built them from. `GenAiInstrumentation` can't reach it. + ### Content capture (PII) Prompt and response content may contain PII, so capture is off by default. diff --git a/packages/genkit-otel/src/genkit_otel/_genai_instrumentation.py b/packages/genkit-otel/src/genkit_otel/_genai_instrumentation.py index c43e3f810..a311a85ba 100644 --- a/packages/genkit-otel/src/genkit_otel/_genai_instrumentation.py +++ b/packages/genkit-otel/src/genkit_otel/_genai_instrumentation.py @@ -23,13 +23,14 @@ from typing import ClassVar, Protocol, TypeVar from opentelemetry import metrics as metrics_api, trace as trace_api -from opentelemetry._logs import get_logger as get_otel_logger +from opentelemetry._logs import get_logger as get_otel_logger, get_logger_provider from opentelemetry.metrics import Meter from opentelemetry.trace import Span, SpanKind, StatusCode, Tracer from opentelemetry.util.types import AttributeValue from pydantic import BaseModel +from pydantic_core import to_jsonable_python -from genkit import Interrupt, ModelResponse, get_logger as get_genkit_logger +from genkit import FinishReason, Interrupt, ModelResponse, get_logger as get_genkit_logger from genkit.model import ModelRequest from genkit.telemetry import Instrumentation, SpanContext, SpanMetadata, SpanNext from genkit_otel._gen_ai_attributes import ( @@ -167,6 +168,19 @@ def _otel_logger(self) -> OtelEventLogger: self._cached_logger = get_otel_logger(self.scope_name) return self._cached_logger + def flush(self) -> None: + """Force-flush the global OTel tracer, meter, and logger providers. + + ``genkit.telemetry.flush_instrumentations()`` calls this, so a + serverless handler can drain buffered spans before the process + freezes. Providers without ``force_flush`` (the API's proxy + defaults) are skipped. Providers behind an injected ``tracer``, + ``meter``, or ``otel_logger`` aren't reachable from here; flush + those on the provider you built. + """ + for provider in (trace_api.get_tracer_provider(), metrics_api.get_meter_provider(), get_logger_provider()): + _force_flush(provider) + async def run_in_new_span( self, metadata: SpanMetadata, @@ -211,13 +225,19 @@ async def _run_model_span( try: output = await next(GenAiSpanContext(span)) response = output if isinstance(output, ModelResponse) else None + # A model can return its failure (finish_reason=failed / error) + # instead of raising; the span still reports it as an error. + error_type = _response_error_type(response) if response is not None else None + failed = error_type is not None if response is not None: - self._add_response_attributes(span, response) + self._add_response_attributes(span, response, failed=failed) + if response is not None and error_type is not None: + self._record_response_failure(span, response, error_type) if self.content_capturing_mode != 'NO_CONTENT': - self._record_content(span, request, response) + self._record_content(span, request, response, failed=failed) self._maybe_capture_action_io(span, metadata.input, output) if self.emit_metrics: - self._record_model_metrics(started, metric_attrs, response=response) + self._record_model_metrics(started, metric_attrs, response=response, error_type=error_type) return output except Interrupt: span.set_attribute('genkit.interrupted', True) @@ -318,8 +338,8 @@ def _record_tool_content(self, span: Span, input: object, output: object) -> Non _set_json_attribute(span, GenAiAttr.TOOL_CALL_RESULT, output) if self._capture_on_event: event_attrs: dict[str, AttributeValue] = { - GenAiAttr.TOOL_CALL_ARGUMENTS: _encode_json_value(input), - GenAiAttr.TOOL_CALL_RESULT: _encode_json_value(output), + GenAiAttr.TOOL_CALL_ARGUMENTS: _safe_encode_json(input), + GenAiAttr.TOOL_CALL_RESULT: _safe_encode_json(output), } _emit_operation_details(self._otel_logger, event_attrs) @@ -329,8 +349,8 @@ def _maybe_capture_action_io(self, span: Span, input: object, output: object) -> _set_json_attribute(span, GenkitAttr.INPUT, input) _set_json_attribute(span, GenkitAttr.OUTPUT, output) - def _add_response_attributes(self, span: Span, response: ModelResponse) -> None: - finish_reasons = _resolve_finish_reasons(response) + def _add_response_attributes(self, span: Span, response: ModelResponse, *, failed: bool) -> None: + finish_reasons = _resolve_finish_reasons(response, failed=failed) if finish_reasons: span.set_attribute(GenAiAttr.RESPONSE_FINISH_REASONS, finish_reasons) usage = response.usage @@ -354,6 +374,8 @@ def _record_content( span: Span, request: ModelRequest | None, response: ModelResponse | None, + *, + failed: bool, ) -> None: input_messages = ( normalize_messages(request.messages) if request is not None and request.messages is not None else None @@ -361,7 +383,7 @@ def _record_content( output_messages: list[dict[str, object]] = [] output_message = resolve_response_message(response) if response is not None else None if output_message is not None and response is not None: - reason = _resolve_finish_reasons(response)[0] + reason = _resolve_finish_reasons(response, failed=failed)[0] output_messages.append(map_output_message(output_message, reason)) if self._capture_on_span: @@ -379,13 +401,18 @@ def _record_content( if self._capture_on_event: event_attrs: dict[str, AttributeValue] = {} if input_messages is not None: - event_attrs[GenAiAttr.INPUT_MESSAGES] = json.dumps(input_messages.messages) + event_attrs[GenAiAttr.INPUT_MESSAGES] = _safe_encode_json(input_messages.messages) if input_messages.system_instructions: - event_attrs[GenAiAttr.SYSTEM_INSTRUCTIONS] = json.dumps(input_messages.system_instructions) + event_attrs[GenAiAttr.SYSTEM_INSTRUCTIONS] = _safe_encode_json(input_messages.system_instructions) if output_messages: - event_attrs[GenAiAttr.OUTPUT_MESSAGES] = json.dumps(output_messages) + event_attrs[GenAiAttr.OUTPUT_MESSAGES] = _safe_encode_json(output_messages) _emit_operation_details(self._otel_logger, event_attrs) + def _record_response_failure(self, span: Span, response: ModelResponse, error_type: str) -> None: + message = response.error.message if response.error is not None else response.finish_message + span.set_status(StatusCode.ERROR, message or None) + span.set_attribute(GenAiAttr.ERROR_TYPE, error_type) + def _record_error(self, span: Span, exc: BaseException) -> None: span.set_status(StatusCode.ERROR, str(exc)) span.set_attribute(GenAiAttr.ERROR_TYPE, type(exc).__name__) @@ -424,10 +451,7 @@ def span_id(self) -> str: def set_metadata(self, metadata: Mapping[str, object]) -> None: for key, value in metadata.items(): - try: - value_string = value if isinstance(value, str) else json.dumps(value) - except (TypeError, ValueError) as exc: - value_string = f'Error encoding metadata: {exc}' + value_string = value if isinstance(value, str) else _safe_encode_json(value) # Keep ad-hoc metadata out of the reserved gen_ai.* namespace. self._span.set_attribute(f'genkit:metadata:{key}', value_string) @@ -488,7 +512,20 @@ def _add_request_config_attributes(attrs: dict[str, AttributeValue], request: Mo attrs[GenAiAttr.OUTPUT_TYPE] = output_type -def _resolve_finish_reasons(response: ModelResponse) -> list[str]: +def _response_error_type(response: ModelResponse) -> str | None: + """``error.type`` for a response that carries its failure, else ``None``. + + The Genkit status (``UNAVAILABLE``...) keeps cardinality low; ``_OTHER`` + is the semconv fallback when the failure has no status. + """ + if response.error is not None: + return response.error.status or '_OTHER' + if response.finish_reason == FinishReason.FAILED: + return '_OTHER' + return None + + +def _resolve_finish_reasons(response: ModelResponse, *, failed: bool) -> list[str]: message = resolve_response_message(response) has_tool_request = any(is_tool_request_part(part) for part in (message.content if message else [])) if has_tool_request: @@ -496,7 +533,7 @@ def _resolve_finish_reasons(response: ModelResponse) -> list[str]: # own stop reason is less specific. return ['tool_calls'] reason = response.finish_reason.value if response.finish_reason is not None else None - return [map_finish_reason(reason, failed=False)] + return [map_finish_reason(reason, failed=failed)] def _config_map(config: object) -> dict[str, object]: @@ -523,26 +560,39 @@ def _encode_json_value(value: object) -> str: """Encode an object as a JSON string, dumping Pydantic models to dicts first. Strings are encoded too (``'ORD-555'`` -> ``'"ORD-555"'``), so every JSON - attribute round-trips through ``json.loads``. Same shape as JS ``JSON.stringify`` - for JSON-safe values. + attribute round-trips through ``json.loads``. """ def _json_default(obj: object) -> object: - if isinstance(obj, BaseModel): - return obj.model_dump(mode='json', by_alias=True, exclude_none=True) - return str(obj) + # datetime -> ISO 8601, UUID/Decimal -> str, dataclass -> dict, bytes -> URL-safe base64. + return to_jsonable_python(obj, by_alias=True, exclude_none=True, bytes_mode='base64', fallback=str) return json.dumps(value, default=_json_default) +def _safe_encode_json(value: object) -> str: + """``_encode_json_value`` that never raises: telemetry must not fail the action.""" + try: + return _encode_json_value(value) + except Exception as exc: # noqa: BLE001 - any encode failure becomes a placeholder. + return f'Unable to encode: {exc}' + + +def _force_flush(provider: object) -> None: + """``provider.force_flush()``; skip proxies without it, log instead of raising.""" + force_flush = getattr(provider, 'force_flush', None) + if not callable(force_flush): + return + try: + force_flush() + except Exception: # noqa: BLE001 - a failed flush must not raise into the app. + logger.warning('OpenTelemetry %s.force_flush() failed', type(provider).__name__, exc_info=True) + + def _set_json_attribute(span: Span, key: str, value: object) -> None: if value is None: return - try: - encoded = _encode_json_value(value) - except (TypeError, ValueError) as exc: - encoded = f'Unable to encode: {exc}' - span.set_attribute(key, encoded) + span.set_attribute(key, _safe_encode_json(value)) def _emit_operation_details(otel_logger: OtelEventLogger, attributes: Mapping[str, AttributeValue]) -> None: diff --git a/packages/genkit-otel/tests/genai_encoding_test.py b/packages/genkit-otel/tests/genai_encoding_test.py index 91681fc79..29d3a03c5 100644 --- a/packages/genkit-otel/tests/genai_encoding_test.py +++ b/packages/genkit-otel/tests/genai_encoding_test.py @@ -51,6 +51,11 @@ def test_nested_pydantic_values_are_encoded() -> None: def test_plain_string_is_json_encoded() -> None: - """A str is JSON-encoded like every other value, so json.loads round-trips it (JS JSON.stringify).""" + """A str is JSON-encoded like every other value, so json.loads round-trips it.""" assert _encode_json_value('table for two') == '"table for two"' assert json.loads(_encode_json_value('table for two')) == 'table for two' + + +def test_non_utf8_bytes_are_base64_encoded() -> None: + """Raw bytes that are not valid UTF-8 encode as URL-safe base64 instead of raising.""" + assert json.loads(_encode_json_value({'raw': b'\xff\xfe'})) == {'raw': '__4='} diff --git a/packages/genkit-otel/tests/genai_instrumentation_test.py b/packages/genkit-otel/tests/genai_instrumentation_test.py index 14c898f2b..60c2e56cf 100644 --- a/packages/genkit-otel/tests/genai_instrumentation_test.py +++ b/packages/genkit-otel/tests/genai_instrumentation_test.py @@ -15,6 +15,7 @@ # SPDX-License-Identifier: Apache-2.0 import asyncio +import datetime import json from collections.abc import Mapping from typing import get_args @@ -26,12 +27,14 @@ CONTENT_ATTRIBUTES, GEN_AI_OPERATION_DETAILS_EVENT, GenAiAttr, + GenAiMetric, GenkitAttr, ) from opentelemetry._logs import LogRecord +from opentelemetry.sdk.metrics.export import MetricsData from opentelemetry.trace import StatusCode -from genkit import FinishReason, Interrupt, Message, ModelResponse, Part, Role +from genkit import Failure, FinishReason, Interrupt, Message, ModelResponse, Part, Role from genkit.model import GenerationUsage, ModelRequest, OutputConfig from genkit.telemetry import SpanContext, SpanMetadata, SpanNext @@ -76,6 +79,13 @@ def _model_response( ) +def _returning(value: object) -> SpanNext[object]: + async def next_fn(span: SpanContext | None = None) -> object: + return value + + return next_fn + + async def _run_model( instr: GenAiInstrumentation, name: str, @@ -182,6 +192,64 @@ async def boom(span=None): assert harness.attr(span, GenAiAttr.ERROR_TYPE) == 'RuntimeError' +@pytest.mark.asyncio +async def test_returned_failure_marks_chat_span_error(harness) -> None: + """A model that returns error=Failure(...) instead of raising still gets an ERROR chat span.""" + instr = harness.instrumentation() + response = ModelResponse( + finish_reason=FinishReason.FAILED, + message=Message(role=Role.MODEL, content=[]), + error=Failure(status='UNAVAILABLE', message='503 Service Unavailable'), + ) + + result = await _run_model(instr, 'googleai/gemini-flash-latest', _model_request(), _returning(response)) + + assert result is response + span = harness.span_named('chat gemini-flash-latest') + assert span is not None + assert span.status.status_code == StatusCode.ERROR + assert span.status.description == '503 Service Unavailable' + assert harness.attr(span, GenAiAttr.ERROR_TYPE) == 'UNAVAILABLE' + assert list(harness.attr(span, GenAiAttr.RESPONSE_FINISH_REASONS)) == ['error'] + duration = [ + dict(point.attributes or {}) + for resource in (harness.metrics.get_metrics_data() or MetricsData(resource_metrics=[])).resource_metrics + for scope in resource.scope_metrics + for metric in scope.metrics + if metric.name == GenAiMetric.OPERATION_DURATION + for point in metric.data.data_points + ] + assert [attrs.get(GenAiAttr.ERROR_TYPE) for attrs in duration] == ['UNAVAILABLE'] + + +@pytest.mark.asyncio +async def test_failed_finish_reason_without_error_uses_other_error_type(harness) -> None: + """finish_reason=failed with no error payload falls back to the semconv _OTHER error.type.""" + instr = harness.instrumentation() + await _run_model( + instr, + 'googleai/gemini-flash-latest', + _model_request(), + _returning(_model_response(finish_reason=FinishReason.FAILED)), + ) + span = harness.span_named('chat gemini-flash-latest') + assert span is not None + assert span.status.status_code == StatusCode.ERROR + assert harness.attr(span, GenAiAttr.ERROR_TYPE) == '_OTHER' + assert list(harness.attr(span, GenAiAttr.RESPONSE_FINISH_REASONS)) == ['error'] + + +@pytest.mark.asyncio +async def test_successful_response_leaves_chat_span_unset(harness) -> None: + """A normal stop response keeps status UNSET and writes no error.type.""" + instr = harness.instrumentation() + await _run_model(instr, 'googleai/gemini-flash-latest', _model_request(), _returning(_model_response())) + span = harness.span_named('chat gemini-flash-latest') + assert span is not None + assert span.status.status_code == StatusCode.UNSET + assert harness.attr(span, GenAiAttr.ERROR_TYPE) is None + + @pytest.mark.asyncio async def test_does_not_capture_content_by_default(harness) -> None: instr = harness.instrumentation() @@ -271,6 +339,37 @@ async def test_span_and_event_writes_both(harness) -> None: assert GEN_AI_OPERATION_DETAILS_EVENT in _event_names(harness) +@pytest.mark.asyncio +@pytest.mark.parametrize('mode', ['EVENT_ONLY', 'SPAN_AND_EVENT']) +async def test_event_capture_encodes_non_json_values_without_failing_the_call(harness, mode: str) -> None: + """A datetime in message history lands as ISO 8601 and the model call still returns.""" + instr = harness.instrumentation(content_capturing_mode=mode) + delivered_at = datetime.datetime(2026, 11, 8, 12, 0, tzinfo=datetime.timezone.utc) + request = _model_request( + messages=[ + Message(role=Role.USER, content=[Part.from_text('when did my order arrive?')]), + Message(role=Role.MODEL, content=[Part.from_tool_request('delivery_status', input={})]), + Message( + role=Role.TOOL, + content=[Part.from_tool_response('delivery_status', output={'delivered_at': delivered_at})], + ), + ] + ) + response = _model_response() + + result = await _run_model(instr, 'googleai/gemini-flash-latest', request, _returning(response)) + + assert result is response + span = harness.span_named('chat gemini-flash-latest') + assert span is not None + assert span.status.status_code == StatusCode.UNSET + record = _operation_details_record(harness) + assert record is not None + raw = str(dict(record.attributes or {})[GenAiAttr.INPUT_MESSAGES]) + assert '2026-11-08T12:00:00Z' in raw + assert isinstance(json.loads(raw), list) + + @pytest.mark.asyncio async def test_nests_flow_and_model_into_one_trace(harness) -> None: instr = harness.instrumentation() @@ -985,3 +1084,82 @@ def fake_get_logger(scope_name: str) -> _RecordedLogger: assert instr._otel_logger is recorded_logger assert instr._otel_logger is recorded_logger assert requested_scopes == ['dining-genai'] + + +class _RecordingProvider: + def __init__(self, *, fail: bool = False) -> None: + self.flushes = 0 + self.fail = fail + + def force_flush(self) -> bool: + self.flushes += 1 + if self.fail: + raise RuntimeError('collector unreachable') + return True + + +def test_flush_instrumentations_force_flushes_global_otel_providers(monkeypatch: pytest.MonkeyPatch) -> None: + """flush_instrumentations() reaches GenAiInstrumentation and force-flushes every global OTel provider.""" + from genkit_otel import _genai_instrumentation + + from genkit.telemetry import ( + FlushableInstrumentation, + configure_instrumentation, + flush_instrumentations, + reset_instrumentation, + ) + + tracer_provider = _RecordingProvider() + meter_provider = _RecordingProvider() + logger_provider = _RecordingProvider() + monkeypatch.setattr(_genai_instrumentation.trace_api, 'get_tracer_provider', lambda: tracer_provider) + monkeypatch.setattr(_genai_instrumentation.metrics_api, 'get_meter_provider', lambda: meter_provider) + monkeypatch.setattr(_genai_instrumentation, 'get_logger_provider', lambda: logger_provider) + + instr = GenAiInstrumentation() + assert isinstance(instr, FlushableInstrumentation) + reset_instrumentation() + configure_instrumentation(instr) + try: + flush_instrumentations() + finally: + reset_instrumentation() + + assert (tracer_provider.flushes, meter_provider.flushes, logger_provider.flushes) == (1, 1, 1) + + +def test_flush_skips_proxy_providers_and_swallows_flush_errors(monkeypatch: pytest.MonkeyPatch) -> None: + """A provider without force_flush is skipped; one that raises doesn't stop the rest or reach the caller.""" + from genkit_otel import _genai_instrumentation + + failing = _RecordingProvider(fail=True) + healthy = _RecordingProvider() + monkeypatch.setattr(_genai_instrumentation.trace_api, 'get_tracer_provider', object) + monkeypatch.setattr(_genai_instrumentation.metrics_api, 'get_meter_provider', lambda: failing) + monkeypatch.setattr(_genai_instrumentation, 'get_logger_provider', lambda: healthy) + + GenAiInstrumentation().flush() + + assert (failing.flushes, healthy.flushes) == (1, 1) + + +@pytest.mark.asyncio +async def test_set_custom_metadata_attributes_encodes_non_json_values(harness) -> None: + """set_custom_metadata_attributes encodes datetime and bytes via _safe_encode_json instead of failing.""" + from datetime import datetime, timezone + + from genkit.telemetry import set_custom_metadata_attributes + + instr = harness.instrumentation() + + async def body(span=None): + if span is not None: + span.set_metadata({'at': datetime(2026, 11, 10, tzinfo=timezone.utc), 'raw': b'\xff'}) + set_custom_metadata_attributes({'tenant': 'acme'}) + return 'ok' + + await instr.run_in_new_span(SpanMetadata(name='myFlow', action_type='flow'), body) + span = harness.span_named('myFlow') + assert span is not None + assert harness.attr(span, 'genkit:metadata:at') == '"2026-11-10T00:00:00Z"' + assert harness.attr(span, 'genkit:metadata:raw') == '"_w=="' diff --git a/packages/genkit/src/genkit/_core/_reflection_v2.py b/packages/genkit/src/genkit/_core/_reflection_v2.py index 41605e05d..0ec2a611e 100644 --- a/packages/genkit/src/genkit/_core/_reflection_v2.py +++ b/packages/genkit/src/genkit/_core/_reflection_v2.py @@ -59,8 +59,7 @@ from genkit._core._reflection import as_agent_input_dict, resolve_agent_init, resolve_runnable_key from genkit._core._reflection_config import REFLECTION_AUTH_ERROR_CODE from genkit._core._registry import Registry -from genkit._core._telemetry._http import connect_developer_ui_collector -from genkit._core._telemetry._instrumentation import flush_instrumentations +from genkit._core._telemetry._http import connect_developer_ui_collector, flush_developer_ui_collector from genkit._core._telemetry._log_exporter import enable_log_export from genkit._core._typing import ( ReflectionCancelActionParams, @@ -441,7 +440,7 @@ async def handle_end_input_stream(self, req_id: str | int | None, params: dict[s stream.close() async def flush_tracing(self) -> None: - await asyncio.to_thread(flush_instrumentations) + await asyncio.to_thread(flush_developer_ui_collector) @staticmethod def run_action_call_options( diff --git a/packages/genkit/src/genkit/_core/_telemetry/_http.py b/packages/genkit/src/genkit/_core/_telemetry/_http.py index e12c39c30..d852c6993 100644 --- a/packages/genkit/src/genkit/_core/_telemetry/_http.py +++ b/packages/genkit/src/genkit/_core/_telemetry/_http.py @@ -45,6 +45,7 @@ SpanMetadata, SpanNext, configure_instrumentation, + instrumentations, is_instrumented_by, parent_path_context, span_is_action, @@ -355,6 +356,18 @@ def connect_developer_ui_collector(*, url: str) -> None: configure_instrumentation(direct_http_for_collector(url=url)) +def flush_developer_ui_collector() -> None: + """Drain the local HTTP trace poster before a run response returns its trace id. + + Flushes ``DirectHttpInstrumentation`` (``DevUIInstrumentation``) only; remote + APM backends (``GenAiInstrumentation``, Cloud Trace, custom providers) stay + isolated from interactive Dev UI clicks. + """ + for inst in instrumentations: + if isinstance(inst, DirectHttpInstrumentation): + inst.flush() + + def maybe_inject_dev_instrumentation() -> None: """``Genkit()`` installs the poster once when a collector URL is set. diff --git a/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py b/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py index cb4263e67..dcb36a475 100644 --- a/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py +++ b/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py @@ -41,6 +41,7 @@ SpanAttributeValue = str | bool | int | float SpanState = Literal['success', 'error'] +"""Value written to ``genkit:state``. ``error`` marks a span whose action returned a failure.""" class SpanNext(Protocol[T_co]): @@ -112,8 +113,8 @@ def dispose(self) -> None: ... class FlushableInstrumentation(Protocol): """Optional: a provider that buffers exports. - ``flush_instrumentations`` calls ``flush`` so a trace is on the wire - before the Developer UI asks for it. + ``flush_instrumentations`` calls ``flush`` so buffered telemetry is on the + wire before a serverless process freezes (or in tests). """ def flush(self) -> None: ... diff --git a/packages/genkit/src/genkit/telemetry/__init__.py b/packages/genkit/src/genkit/telemetry/__init__.py index 66b857245..914177cb7 100644 --- a/packages/genkit/src/genkit/telemetry/__init__.py +++ b/packages/genkit/src/genkit/telemetry/__init__.py @@ -19,6 +19,8 @@ Application code should call :class:`genkit.Genkit`. ``genkit start`` records to the Developer UI. ``configure_instrumentation`` is the hook for a recording backend; ``reset_instrumentation`` starts over between tests. +``set_custom_metadata_attributes`` stamps the active span (``tenant_id``), +and ``flush_instrumentations`` drains exports before a serverless shutdown. """ from genkit._core._telemetry._instrumentation import ( @@ -29,9 +31,11 @@ SpanMetadata, SpanNext, configure_instrumentation, + flush_instrumentations, is_instrumented_by, reset_instrumentation, run_in_new_span, + set_custom_metadata_attributes, ) __all__ = [ @@ -44,6 +48,9 @@ 'SpanNext', 'configure_instrumentation', 'run_in_new_span', + # App helpers + 'flush_instrumentations', + 'set_custom_metadata_attributes', # Testing & test-inspection helpers 'is_instrumented_by', 'reset_instrumentation', diff --git a/packages/genkit/tests/genkit/core/developer_ui_handshake_test.py b/packages/genkit/tests/genkit/core/developer_ui_handshake_test.py index e332f2e1f..1a203cb5a 100644 --- a/packages/genkit/tests/genkit/core/developer_ui_handshake_test.py +++ b/packages/genkit/tests/genkit/core/developer_ui_handshake_test.py @@ -290,3 +290,41 @@ def test_poster_reuses_one_worker(monkeypatch: pytest.MonkeyPatch) -> None: assert set(threading.enumerate()) - before == {sink.worker} finally: sink.shutdown() + + +@pytest.mark.asyncio +async def test_dev_ui_run_flush_flushes_dev_ui_collector_only() -> None: + """Before a run response, the reflection server drains DevUIInstrumentation only, not remote APM backends.""" + + class RecordingSink: + def __init__(self) -> None: + self.flushes = 0 + + def export_spans(self, spans: Any, *, resource_attributes: Any) -> None: # noqa: ANN401 + pass + + def flush(self) -> None: + self.flushes += 1 + + def shutdown(self) -> None: + pass + + class RemoteBackend: + def __init__(self) -> None: + self.flushes = 0 + + async def run_in_new_span(self, metadata: Any, next: Any) -> Any: # noqa: ANN401 + return await next() + + def flush(self) -> None: + self.flushes += 1 + + dev_sink = RecordingSink() + remote = RemoteBackend() + configure_instrumentation(DevUIInstrumentation(dev_sink)) # type: ignore[arg-type] + configure_instrumentation(remote) + + await _handshake_server().flush_tracing() + + assert dev_sink.flushes == 1 + assert remote.flushes == 0 diff --git a/packages/genkit/tests/genkit/core/instrumentation_test.py b/packages/genkit/tests/genkit/core/instrumentation_test.py index 6514ee1d3..cf7243352 100644 --- a/packages/genkit/tests/genkit/core/instrumentation_test.py +++ b/packages/genkit/tests/genkit/core/instrumentation_test.py @@ -12,20 +12,19 @@ import pytest from genkit._core._action import Action -from genkit._core._telemetry._instrumentation import ( - flush_instrumentations, - set_custom_metadata_attributes, - set_span_state, -) +from genkit._core._telemetry import _instrumentation as core_instrumentation +from genkit._core._telemetry._instrumentation import set_span_state from genkit.plugin_api import ActionKind from genkit.telemetry import ( FlushableInstrumentation, SpanContext, SpanMetadata, configure_instrumentation, + flush_instrumentations, is_instrumented_by, reset_instrumentation, run_in_new_span, + set_custom_metadata_attributes, ) @@ -330,6 +329,19 @@ def test_telemetry_exports_provider_types() -> None: assert 'instrumentations' not in telemetry.__all__ +def test_span_metadata_and_flush_helpers_are_public() -> None: + """App code stamps tenant metadata and flushes on shutdown via genkit.telemetry, not genkit._core.""" + import genkit.telemetry as telemetry + + for name in ('set_custom_metadata_attributes', 'flush_instrumentations'): + assert name in telemetry.__all__ + assert getattr(telemetry, name) is getattr(core_instrumentation, name) + # Genkit writes genkit:state itself, and dispose already runs at exit. + for name in ('set_span_state', 'SpanState', 'dispose_instrumentations'): + assert name not in telemetry.__all__ + assert not hasattr(telemetry, name) + + def test_flush_instrumentations_flushes_flushable() -> None: """flush_instrumentations calls flush() on a provider implementing FlushableInstrumentation."""