diff --git a/packages/genkit/src/genkit/_core/_error.py b/packages/genkit/src/genkit/_core/_error.py index 48516ad30..4edcfddb0 100644 --- a/packages/genkit/src/genkit/_core/_error.py +++ b/packages/genkit/src/genkit/_core/_error.py @@ -22,6 +22,7 @@ import math import reprlib import time +import traceback from collections.abc import Mapping, Sequence from dataclasses import dataclass from email.utils import parsedate_to_datetime @@ -1034,3 +1035,8 @@ def get_error_stack(error: object) -> str | None: # For now, return an empty string to keep Dev UI clean as per requirements. return '' return None + + +def format_exception_traceback(exc: BaseException) -> str: + """Format an exception and its traceback chain as a single string.""" + return ''.join(traceback.format_exception(type(exc), exc, exc.__traceback__)) diff --git a/packages/genkit/src/genkit/_core/_reflection.py b/packages/genkit/src/genkit/_core/_reflection.py index 2ca30fc0d..699b22243 100644 --- a/packages/genkit/src/genkit/_core/_reflection.py +++ b/packages/genkit/src/genkit/_core/_reflection.py @@ -23,7 +23,6 @@ import os import signal import threading -import traceback from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable from contextlib import asynccontextmanager from dataclasses import dataclass, field @@ -43,7 +42,7 @@ from genkit._core._action import Action, BidiAction, input_from_json, parse_action_key from genkit._core._constants import GENKIT_VERSION from genkit._core._environment import is_dev_environment -from genkit._core._error import Interrupt, get_reflection_json, interrupt_escape_error +from genkit._core._error import Interrupt, format_exception_traceback, get_reflection_json, interrupt_escape_error from genkit._core._logger import get_logger from genkit._core._middleware import _MiddlewareMetadata from genkit._core._model import AgentInit, AgentInput, ModelRef @@ -187,7 +186,7 @@ async def execute(self) -> None: error = get_reflection_json(interrupt_escape_error(e) or e, trace_id=self.trace_id) if error.details is not None and not error.details.stack and e.__traceback__: # Same as v2: `genkit flow:run` prints this, so give it Python frames. - stack = ''.join(traceback.format_exception(type(e), e, e.__traceback__)) + stack = format_exception_traceback(e) error = error.model_copy(update={'details': error.details.model_copy(update={'stack': stack})}) response_json = json.dumps({'error': error.model_dump(by_alias=True)}) diff --git a/packages/genkit/src/genkit/_core/_reflection_v2.py b/packages/genkit/src/genkit/_core/_reflection_v2.py index d92b0d286..4468e1df4 100644 --- a/packages/genkit/src/genkit/_core/_reflection_v2.py +++ b/packages/genkit/src/genkit/_core/_reflection_v2.py @@ -34,7 +34,6 @@ import asyncio import json import os -import traceback from collections.abc import Awaitable, Callable, Coroutine from typing import Any @@ -50,6 +49,7 @@ ReflectionError, ReflectionErrorDetails, StatusCodes, + format_exception_traceback, get_reflection_json, interrupt_escape_error, ) @@ -534,7 +534,7 @@ async def send_run_action_error( ref = get_reflection_json(exc) stack = ref.details.stack if ref.details else None if not stack and exc.__traceback__: - stack = ''.join(traceback.format_exception(type(exc), exc, exc.__traceback__)) + stack = format_exception_traceback(exc) tid = trace_holder[0] or (ref.details.trace_id if ref.details else None) status = ReflectionError( code=ref.code, diff --git a/packages/genkit/src/genkit/_core/_telemetry/_http.py b/packages/genkit/src/genkit/_core/_telemetry/_http.py index 86219f416..2672ec185 100644 --- a/packages/genkit/src/genkit/_core/_telemetry/_http.py +++ b/packages/genkit/src/genkit/_core/_telemetry/_http.py @@ -14,9 +14,12 @@ # # SPDX-License-Identifier: Apache-2.0 -"""Developer UI trace poster that POSTs OTLP/JSON. No OpenTelemetry runtime. +"""Developer UI trace poster that POSTs TraceData to ``/api/traces``. No OpenTelemetry runtime. -Logs reach the Developer UI through Genkit's own log exporter, not here. +Spans go to ``/api/traces`` rather than ``/api/otlp`` because the collector's +OTLP converter drops span events, and the Traces tab reads a failed span's +heading and stack from its ``exception`` event. Logs reach the Developer UI +through Genkit's own log exporter (``/api/otlp``), not here. """ from __future__ import annotations @@ -24,6 +27,7 @@ import asyncio import contextlib import json +import math import os import secrets import threading @@ -37,7 +41,7 @@ from urllib.parse import urljoin, urlparse from .._environment import is_dev_environment -from .._error import GenkitError, Interrupt, _StreamingCallbackError +from .._error import GenkitError, Interrupt, _StreamingCallbackError, format_exception_traceback from .._logger import get_logger from .._reflection_config import reflection_enabled from ._attrs import Attr, State, metadata_key @@ -65,6 +69,9 @@ # The Developer UI flushes right before it reads a trace. A hung collector # should cost it a couple of seconds, not the full export timeout. FLUSH_TIMEOUT_SECONDS = 2.0 +# Cross-SDK value for each span's ``instrumentationLibrary`` field in the +# /api/traces body. +INSTRUMENTATION_LIBRARY = {'name': 'genkit-tracer', 'version': 'v1'} @dataclass @@ -78,6 +85,9 @@ class ActiveSpan: attributes: dict[str, object] = field(default_factory=dict) status_code: int = 0 status_message: str | None = None + # exception.type / .message / .stacktrace, formatted when the span fails. + # Plain strings, so a finished span holds no traceback frames. + exception: dict[str, str] | None = field(default=None, repr=False, compare=False) parent: ActiveSpan | None = field(default=None, repr=False, compare=False) has_failed_child: bool = field(default=False, repr=False, compare=False) @@ -138,56 +148,92 @@ def new_span_id() -> str: return secrets.token_hex(8) -def encode_attribute_value(value: object) -> dict[str, object]: - if isinstance(value, str): - return {'stringValue': value} - if isinstance(value, bool): - return {'boolValue': value} - if isinstance(value, int) and not isinstance(value, bool): - return {'intValue': value} - if isinstance(value, float): - return {'doubleValue': value} - return {'stringValue': str(value)} +def exception_attributes(exc: BaseException) -> dict[str, str]: + """The attributes OpenTelemetry's ``Span.record_exception`` writes, minus ``exception.escaped``. + An empty ``str(exc)`` leaves ``exception.message`` out, so the Traces tab + falls back to its generic heading instead of a blank one. + """ + cls = type(exc) + module = cls.__module__ + attrs = {'exception.type': f'{module}.{cls.__qualname__}' if module and module != 'builtins' else cls.__qualname__} + message = str(exc) + if message: + attrs['exception.message'] = message + attrs['exception.stacktrace'] = format_exception_traceback(exc) + return attrs + + +def nanos_to_millis(nanos: int) -> float: + return nanos / 1_000_000 + + +def encode_attribute_value(value: object) -> str | bool | int | float: + # NaN and infinity aren't JSON; the collector would reject the whole trace. + if isinstance(value, float) and not math.isfinite(value): + return str(value) + if isinstance(value, (str, bool, int, float)): + return value + return str(value) -def encode_attributes(attributes: dict[str, object]) -> list[dict[str, object]]: - return [{'key': key, 'value': encode_attribute_value(value)} for key, value in attributes.items()] +def encode_span(span: ActiveSpan) -> dict[str, object]: + """One ``SpanData`` in the shape the collector's ``/api/traces`` schema takes. -def encode_span(span: ActiveSpan, *, resource_attributes: dict[str, object]) -> dict[str, object]: + The start export has ``endTime`` 0, which the collector and the Traces tab + read as still running. The end export replaces it in the collector's store. + """ + end_time = nanos_to_millis(span.end_time_unix_nano) if span.end_time_unix_nano else 0 + status: dict[str, object] = {'code': span.status_code} + if span.status_message: + status['message'] = span.status_message + time_events: list[dict[str, object]] = [] + if span.exception is not None and span.end_time_unix_nano: + time_events.append({ + 'time': end_time, + 'annotation': {'description': 'exception', 'attributes': dict(span.exception)}, + }) body: dict[str, object] = { - 'traceId': span.trace_id, 'spanId': span.span_id, - 'name': span.name, - 'kind': 1, - 'startTimeUnixNano': str(span.start_time_unix_nano), - 'endTimeUnixNano': str(span.end_time_unix_nano), - 'attributes': encode_attributes(span.attributes), - 'droppedAttributesCount': 0, - 'events': [], - 'droppedEventsCount': 0, - 'status': {'code': span.status_code, 'message': span.status_message}, + 'traceId': span.trace_id, + 'startTime': nanos_to_millis(span.start_time_unix_nano), + 'endTime': end_time, + 'attributes': {key: encode_attribute_value(value) for key, value in span.attributes.items()}, + 'displayName': span.name, 'links': [], - 'droppedLinksCount': 0, + 'instrumentationLibrary': dict(INSTRUMENTATION_LIBRARY), + 'spanKind': 'INTERNAL', + 'sameProcessAsParentSpan': {'value': True}, + 'status': status, + 'timeEvents': {'timeEvent': time_events}, } if span.parent_span_id: body['parentSpanId'] = span.parent_span_id - return { - 'resource': { - 'attributes': encode_attributes(resource_attributes), - 'droppedAttributesCount': 0, - }, - 'scopeSpans': [ - { - 'scope': {'name': 'genkit-python', 'version': ''}, - 'spans': [body], - } - ], + return body + + +def encode_trace(span: ActiveSpan) -> dict[str, object]: + """One ``TraceData`` payload for a single span in the collector's ``/api/traces`` schema. + + Only the root span sets the trace's ``displayName`` and ``startTime``. + ``endTime`` stays off until the root ends, so the Traces tab lists the + trace as running until then. + """ + encoded = encode_span(span) + trace: dict[str, object] = { + 'traceId': span.trace_id, + 'spans': {span.span_id: encoded}, } + if span.parent_span_id is None: + trace['displayName'] = span.name + trace['startTime'] = encoded['startTime'] + if span.end_time_unix_nano: + trace['endTime'] = encoded['endTime'] + return trace -def collector_otlp_url(server: str) -> str: - return urljoin(server.rstrip('/') + '/', 'api/otlp') +def collector_traces_url(server: str) -> str: + return urljoin(server.rstrip('/') + '/', 'api/traces') def post_json(*, url: str, body: str) -> None: @@ -204,7 +250,7 @@ def post_json(*, url: str, body: str) -> None: class CollectorHttpSink: - """POSTs OTLP/JSON spans to the collector from one background worker.""" + """POSTs TraceData to the collector's ``/api/traces`` from one background worker.""" def __init__(self, url: str) -> None: self.url = url @@ -213,14 +259,16 @@ def __init__(self, url: str) -> None: self.worker = threading.Thread(target=self.run_worker, name='genkit-trace-export', daemon=True) self.worker.start() - def export_spans(self, spans: list[ActiveSpan], *, resource_attributes: dict[str, object]) -> None: + def export_spans(self, spans: list[ActiveSpan]) -> None: + # Encoded on the caller's thread: the start export has to snapshot the + # span before the body goes on to change it. if self.closed or not spans: return - payload = {'resourceSpans': [encode_span(span, resource_attributes=resource_attributes) for span in spans]} - try: - self.queue.put_nowait(json.dumps(payload)) - except Full: - logger.debug('Developer UI trace export queue is full; dropping spans') + for span in spans: + try: + self.queue.put_nowait(json.dumps(encode_trace(span))) + except Full: + logger.debug('Developer UI trace export queue is full; dropping spans') def run_worker(self) -> None: while True: @@ -252,14 +300,8 @@ class DirectHttpInstrumentation: does not count as the tab already being on. """ - def __init__( - self, - sink: CollectorHttpSink, - *, - resource_attributes: dict[str, object] | None = None, - ) -> None: + def __init__(self, sink: CollectorHttpSink) -> None: self.sink = sink - self.resource_attributes = resource_attributes or {'service.name': 'genkit-python'} async def run_in_new_span( self, @@ -280,7 +322,7 @@ async def run_in_new_span( ) if parent is None: span.attributes[Attr.IS_ROOT] = True - self.sink.export_spans([span], resource_attributes=self.resource_attributes) + self.sink.export_spans([span]) path_token = parent_path_context.set(qualified_path) parent_token = _parent_span.set(span) ctx = DirectSpanContext(span) @@ -296,6 +338,8 @@ async def run_in_new_span( except Interrupt as e: # the Dev UI draws an interrupted tool from the error state plus # genkit:metadata:interrupt; generate above it still succeeds. + # No exception event: the Traces tab titles the span + # "Interrupted" only when there's no exception message. span.attributes[Attr.STATE] = State.ERROR span.status_code = 2 mark_failure_source(span=span, exc=e) @@ -304,17 +348,23 @@ async def run_in_new_span( raise except (Exception, _StreamingCallbackError) as e: actual = e.__cause__ if isinstance(e, _StreamingCallbackError) and e.__cause__ is not None else e - span.attributes[Attr.STATE] = State.ERROR - err_text = actual.message if isinstance(actual, GenkitError) else str(actual) - span.attributes[Attr.ERROR] = err_text - span.status_code = 2 - span.status_message = str(actual) - note_child_failed(span) - mark_failure_source(span=span, exc=actual) - raise + try: + span.attributes[Attr.STATE] = State.ERROR + err_text = actual.message if isinstance(actual, GenkitError) else str(actual) + span.attributes[Attr.ERROR] = err_text + span.status_code = 2 + span.status_message = str(actual) + # The Traces tab heading reads exception.message and the stack + # box reads exception.stacktrace. + span.exception = exception_attributes(actual) + note_child_failed(span) + mark_failure_source(span=span, exc=actual) + raise + finally: + actual = None finally: span.end_time_unix_nano = now_unix_nano() - self.sink.export_spans([span], resource_attributes=self.resource_attributes) + self.sink.export_spans([span]) _parent_span.reset(parent_token) parent_path_context.reset(path_token) @@ -379,7 +429,7 @@ def telemetry_server_url() -> str | None: def direct_http_for_collector(*, url: str) -> DevUIInstrumentation: - return DevUIInstrumentation(CollectorHttpSink(collector_otlp_url(url))) + return DevUIInstrumentation(CollectorHttpSink(collector_traces_url(url))) def genkit_dev_instrumentation() -> Instrumentation | None: diff --git a/packages/genkit/tests/genkit/conftest.py b/packages/genkit/tests/genkit/conftest.py index c8f433e8d..3b098d75d 100644 --- a/packages/genkit/tests/genkit/conftest.py +++ b/packages/genkit/tests/genkit/conftest.py @@ -26,7 +26,7 @@ class MemoryCollectorSink: def __init__(self) -> None: self._spans: list[ActiveSpan] = [] - def export_spans(self, spans: list[ActiveSpan], *, resource_attributes: dict[str, object]) -> None: + def export_spans(self, spans: list[ActiveSpan]) -> None: self._spans.extend(spans) def flush(self) -> None: 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 3182aace8..c95ccddeb 100644 --- a/packages/genkit/tests/genkit/core/developer_ui_handshake_test.py +++ b/packages/genkit/tests/genkit/core/developer_ui_handshake_test.py @@ -278,11 +278,11 @@ def test_poster_reuses_one_worker(monkeypatch: pytest.MonkeyPatch) -> None: posted: list[str] = [] monkeypatch.setattr(http_telemetry, 'post_json', lambda *, url, body: posted.append(body)) before = set(threading.enumerate()) - sink = CollectorHttpSink('http://127.0.0.1:4041/api/otlp') + sink = CollectorHttpSink('http://127.0.0.1:4041/api/traces') span = ActiveSpan(trace_id='t' * 32, span_id='s' * 16, parent_span_id=None, name='x', start_time_unix_nano=1) try: for _ in range(200): - sink.export_spans([span], resource_attributes={}) + sink.export_spans([span]) sink.flush() assert len(posted) == 200 @@ -300,7 +300,7 @@ class RecordingSink: def __init__(self) -> None: self.flushes = 0 - def export_spans(self, spans: Any, *, resource_attributes: Any) -> None: # noqa: ANN401 + def export_spans(self, spans: Any) -> None: # noqa: ANN401 pass def flush(self) -> None: @@ -335,7 +335,7 @@ async def test_dev_ui_run_flush_ignores_broken_collector_sink() -> None: """A raising Dev UI collector sink does not fail reflection v2 flush_tracing.""" class BrokenSink: - def export_spans(self, spans: Any, *, resource_attributes: Any) -> None: # noqa: ANN401 + def export_spans(self, spans: Any) -> None: # noqa: ANN401 pass def flush(self) -> None: diff --git a/packages/genkit/tests/genkit/core/endpoints/reflection_test.py b/packages/genkit/tests/genkit/core/endpoints/reflection_test.py index 1c3853734..4845a06d6 100644 --- a/packages/genkit/tests/genkit/core/endpoints/reflection_test.py +++ b/packages/genkit/tests/genkit/core/endpoints/reflection_test.py @@ -630,7 +630,7 @@ async def test_run_action_flushes_dev_ui_collector_only() -> None: events: list[str] = [] class RecordingSink: - def export_spans(self, spans: Any, *, resource_attributes: Any) -> None: # noqa: ANN401 + def export_spans(self, spans: Any) -> None: # noqa: ANN401 pass def flush(self) -> None: @@ -676,7 +676,7 @@ async def test_run_action_succeeds_when_dev_ui_collector_flush_raises() -> None: from genkit._core._telemetry._instrumentation import configure_instrumentation, reset_instrumentation class BrokenSink: - def export_spans(self, spans: Any, *, resource_attributes: Any) -> None: # noqa: ANN401 + def export_spans(self, spans: Any) -> None: # noqa: ANN401 pass def flush(self) -> None: diff --git a/packages/genkit/tests/genkit/core/telemetry/trace_data_encoder_test.py b/packages/genkit/tests/genkit/core/telemetry/trace_data_encoder_test.py new file mode 100644 index 000000000..0fa679b48 --- /dev/null +++ b/packages/genkit/tests/genkit/core/telemetry/trace_data_encoder_test.py @@ -0,0 +1,410 @@ +# 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. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The TraceData the Dev UI poster sends to ``/api/traces``, and what the Traces tab reads from it.""" + +from __future__ import annotations + +import gc +import json +import weakref +from collections.abc import Generator +from typing import Any + +import pytest + +from genkit import Genkit, GenkitError, Interrupt, Message, ModelResponse, Part +from genkit._core._error import _StreamingCallbackError +from genkit._core._model import ModelRequest +from genkit._core._telemetry._http import ( + ActiveSpan, + DirectHttpInstrumentation, + collector_traces_url, + encode_trace, +) +from genkit._core._typing import FinishReason, Role, ToolRequest +from genkit.model import ModelContext +from genkit.telemetry import SpanContext, configure_instrumentation, reset_instrumentation, run_in_new_span + + +class SnapshotSink: + """Encodes at export time, like CollectorHttpSink, so the start export keeps its in-progress shape.""" + + def __init__(self) -> None: + self.posts: list[dict[str, Any]] = [] + + def export_spans(self, spans: list[ActiveSpan]) -> None: + self.posts.extend(json.loads(json.dumps(encode_trace(span))) for span in spans) + + def flush(self) -> None: + return + + def shutdown(self) -> None: + return + + def exports(self, name: str) -> list[dict[str, Any]]: + """Every export of the span called ``name``, start first.""" + return [span for post in self.posts for span in post['spans'].values() if span['displayName'] == name] + + def final(self, name: str) -> dict[str, Any]: + (*_, last) = self.exports(name) + return last + + def trace_posts(self, name: str) -> list[dict[str, Any]]: + return [post for post in self.posts if any(s['displayName'] == name for s in post['spans'].values())] + + +@pytest.fixture +def sink() -> Generator[SnapshotSink, None, None]: + recorder = SnapshotSink() + reset_instrumentation() + configure_instrumentation(DirectHttpInstrumentation(recorder)) # type: ignore[arg-type] + try: + yield recorder + finally: + reset_instrumentation() + + +def exception_event(span: dict[str, Any]) -> dict[str, Any] | None: + events = [e for e in span['timeEvents']['timeEvent'] if e['annotation']['description'] == 'exception'] + return events[0]['annotation']['attributes'] if events else None + + +def dev_ui_heading(span: dict[str, Any]) -> str: + """The error heading genkit-ui's span details shows for a non-model span. + + Mirrors ``errorMessage`` in span-details.component.ts and + ``isSpanInterrupted`` in utils/trace.ts. + """ + exception = exception_event(span) or {} + if exception.get('exception.message'): + return str(exception['exception.message']) + attrs = span['attributes'] + interrupted = attrs.get('genkit:metadata:subtype') == 'tool' and bool(attrs.get('genkit:metadata:interrupt')) + return 'Interrupted' if interrupted else 'Error' + + +def calls_tool(name: str) -> ModelResponse: + return ModelResponse( + finish_reason=FinishReason.STOP, + message=Message( + role=Role.MODEL, + content=[Part(tool_request=ToolRequest(name=name, ref=f'ref-{name}', input={}))], + ), + ) + + +def scripted_model(ai: Genkit, turns: list[ModelResponse]) -> None: + async def model(_request: ModelRequest, _ctx: ModelContext) -> ModelResponse: + return turns.pop(0) + + ai.define_model(name='kitchen-model', fn=model) + + +def test_traces_url_targets_api_traces() -> None: + """Spans go to /api/traces; /api/otlp drops span events.""" + assert collector_traces_url('http://127.0.0.1:4033') == 'http://127.0.0.1:4033/api/traces' + assert collector_traces_url('http://127.0.0.1:4033/') == 'http://127.0.0.1:4033/api/traces' + + +@pytest.mark.asyncio +async def test_successful_span_encodes_as_span_data(sink: SnapshotSink) -> None: + """A finished span carries the SpanData fields the collector schema requires, in milliseconds.""" + + async def plate_order(_span: SpanContext) -> str: + return 'plated' + + await run_in_new_span('plateOrder', plate_order, input={'order': 1042}) + + span = sink.final('plateOrder') + assert set(span) == { + 'spanId', + 'traceId', + 'startTime', + 'endTime', + 'attributes', + 'displayName', + 'links', + 'instrumentationLibrary', + 'spanKind', + 'sameProcessAsParentSpan', + 'status', + 'timeEvents', + } + assert span['instrumentationLibrary'] == {'name': 'genkit-tracer', 'version': 'v1'} + assert span['spanKind'] == 'INTERNAL' + assert span['status'] == {'code': 1} + assert span['timeEvents'] == {'timeEvent': []} + assert span['attributes']['genkit:state'] == 'success' + assert span['attributes']['genkit:output'] == '"plated"' + # milliseconds since the epoch, not nanoseconds + assert 1e12 < span['startTime'] <= span['endTime'] < 1e14 + + +@pytest.mark.asyncio +async def test_start_export_is_in_progress_and_end_export_closes_the_trace(sink: SnapshotSink) -> None: + """The start export has endTime 0 and no trace endTime; the end export sets both.""" + + async def fire_ticket(_span: SpanContext) -> str: + return 'fired' + + await run_in_new_span('fireTicket', fire_ticket) + + started, ended = sink.trace_posts('fireTicket') + (start_span,) = started['spans'].values() + assert start_span['endTime'] == 0 + assert start_span['status'] == {'code': 0} + assert 'genkit:state' not in start_span['attributes'] + assert started['displayName'] == 'fireTicket' + assert started['startTime'] == start_span['startTime'] + assert 'endTime' not in started + + (end_span,) = ended['spans'].values() + assert end_span['spanId'] == start_span['spanId'] + assert ended['endTime'] == end_span['endTime'] > 0 + + +@pytest.mark.asyncio +async def test_child_span_links_to_parent_and_leaves_trace_fields_to_the_root(sink: SnapshotSink) -> None: + """A child carries parentSpanId and the root's traceId; only the root sets the trace's name and times.""" + + async def check_pantry(_span: SpanContext) -> str: + return 'stocked' + + async def place_order(_span: SpanContext) -> str: + return await run_in_new_span('checkPantry', check_pantry) + + await run_in_new_span('placeOrder', place_order) + + order, pantry = sink.final('placeOrder'), sink.final('checkPantry') + assert 'parentSpanId' not in order + assert pantry['parentSpanId'] == order['spanId'] + assert pantry['traceId'] == order['traceId'] + for post in sink.trace_posts('checkPantry'): + assert set(post) == {'traceId', 'spans'} + + +@pytest.mark.asyncio +async def test_attributes_keep_their_json_types(sink: SnapshotSink) -> None: + """Attributes encode as a flat map: str, bool, int and float stay typed; structured input is a JSON string.""" + + async def weigh_flour(span: SpanContext) -> None: + span.set_metadata({'station': 'pastry'}) + + await run_in_new_span( + 'weighFlour', + weigh_flour, + input={'grams': 500, 'sifted': True}, + attributes={'kitchen.open': True, 'kitchen.covers': 48, 'kitchen.load': 0.75, 'kitchen.nan': float('nan')}, + ) + + attrs = sink.final('weighFlour')['attributes'] + assert attrs['kitchen.open'] is True + assert attrs['kitchen.covers'] == 48 + assert attrs['kitchen.load'] == 0.75 + # NaN isn't JSON; a bare NaN would make the collector reject the whole trace. + assert attrs['kitchen.nan'] == 'nan' + assert attrs['genkit:metadata:station'] == 'pastry' + assert json.loads(attrs['genkit:input']) == {'grams': 500, 'sifted': True} + assert attrs['genkit:isRoot'] is True + + +@pytest.mark.asyncio +async def test_failed_span_records_exception_event_with_type_message_and_stacktrace(sink: SnapshotSink) -> None: + """A raised error lands as an exception event the Traces tab reads for its heading and stack box.""" + + async def check_allergens(_span: SpanContext) -> None: + raise ValueError('allergen db unavailable') + + with pytest.raises(ValueError): + await run_in_new_span('checkAllergens', check_allergens) + + start, end = sink.exports('checkAllergens') + assert exception_event(start) is None + assert end['status'] == {'code': 2, 'message': 'allergen db unavailable'} + (event,) = end['timeEvents']['timeEvent'] + assert event['time'] == end['endTime'] + attrs = event['annotation']['attributes'] + assert attrs['exception.type'] == 'ValueError' + assert attrs['exception.message'] == 'allergen db unavailable' + assert attrs['exception.stacktrace'].startswith('Traceback (most recent call last):') + assert 'in check_allergens' in attrs['exception.stacktrace'] + assert attrs['exception.stacktrace'].rstrip().endswith('ValueError: allergen db unavailable') + assert dev_ui_heading(end) == 'allergen db unavailable' + + +@pytest.mark.asyncio +async def test_error_propagating_through_a_flow_fails_both_spans_with_the_message(sink: SnapshotSink) -> None: + """A tool error that escapes the flow shows its message on the tool span and on the flow span.""" + ai = Genkit() + + @ai.tool() + async def check_allergens(dish: str) -> str: + raise ValueError('allergen db unavailable') + + @ai.flow() + async def take_order(dish: str) -> str: + return await check_allergens(dish) + + with pytest.raises(ValueError): + await take_order('pad thai') + + tool, flow = sink.final('check_allergens'), sink.final('take_order') + assert dev_ui_heading(tool) == dev_ui_heading(flow) == 'allergen db unavailable' + assert tool['parentSpanId'] == flow['spanId'] + assert tool['attributes']['genkit:isFailureSource'] is True + assert 'genkit:isFailureSource' not in flow['attributes'] + + +@pytest.mark.asyncio +async def test_genkit_error_message_is_the_full_string(sink: SnapshotSink) -> None: + """exception.message is str(err), status prefix and cause included, the same text as status.message.""" + + async def reserve_table(_span: SpanContext) -> None: + raise GenkitError(status='UNAVAILABLE', message='booking service down', cause=TimeoutError('after 5s')) + + with pytest.raises(GenkitError): + await run_in_new_span('reserveTable', reserve_table) + + span = sink.final('reserveTable') + attrs = exception_event(span) + assert attrs is not None + assert attrs['exception.type'] == 'genkit._core._error.GenkitError' + assert attrs['exception.message'] == 'UNAVAILABLE: booking service down: after 5s' + assert span['status']['message'] == attrs['exception.message'] + assert span['attributes']['genkit:error'] == 'booking service down' + + +@pytest.mark.asyncio +async def test_empty_message_leaves_exception_message_out(sink: SnapshotSink) -> None: + """A bare TimeoutError() still records its type and stack, without a blank heading.""" + + async def wait_for_oven(_span: SpanContext) -> None: + raise TimeoutError + + with pytest.raises(TimeoutError): + await run_in_new_span('waitForOven', wait_for_oven) + + attrs = exception_event(sink.final('waitForOven')) + assert attrs is not None + assert attrs['exception.type'] == 'TimeoutError' + assert 'exception.message' not in attrs + assert 'TimeoutError' in attrs['exception.stacktrace'] + + +@pytest.mark.asyncio +async def test_stream_callback_failure_records_the_callback_error(sink: SnapshotSink) -> None: + """The internal stream-callback carrier is unwrapped; the event names what the callback raised.""" + + async def stream_receipt(_span: SpanContext) -> None: + try: + raise ConnectionResetError('printer offline') + except ConnectionResetError as e: + raise _StreamingCallbackError from e + + with pytest.raises(_StreamingCallbackError): + await run_in_new_span('streamReceipt', stream_receipt) + + attrs = exception_event(sink.final('streamReceipt')) + assert attrs is not None + assert attrs['exception.type'] == 'ConnectionResetError' + assert attrs['exception.message'] == 'printer offline' + assert '_StreamingCallbackError' not in attrs['exception.stacktrace'] + + +@pytest.mark.asyncio +async def test_finished_span_holds_strings_not_the_exception() -> None: + """The recorded exception is formatted text, so a finished span keeps no traceback frames alive.""" + held: list[ActiveSpan] = [] + + class HoldingSink(SnapshotSink): + def export_spans(self, spans: list[ActiveSpan]) -> None: + held.extend(spans) + + class _LocalSentinel: + pass + + local_ref: weakref.ref[_LocalSentinel] | None = None + + async def charge_card(_span: SpanContext) -> None: + nonlocal local_ref + sentinel = _LocalSentinel() + local_ref = weakref.ref(sentinel) + raise RuntimeError('card declined') + + was_gc_enabled = gc.isenabled() + gc.disable() + reset_instrumentation() + configure_instrumentation(DirectHttpInstrumentation(HoldingSink())) # type: ignore[arg-type] + try: + try: + await run_in_new_span('chargeCard', charge_card) + except RuntimeError: + pass + assert local_ref is not None + assert local_ref() is None + finally: + reset_instrumentation() + if was_gc_enabled: + gc.enable() + + exception = held[-1].exception + assert exception is not None + assert all(isinstance(v, str) for v in exception.values()) + + +@pytest.mark.asyncio +async def test_interrupted_tool_renders_as_interrupted(sink: SnapshotSink) -> None: + """An Interrupt records no exception event, so the Traces tab titles the tool span Interrupted.""" + ai = Genkit() + scripted_model(ai, [calls_tool('approve_comp')]) + + @ai.tool(name='approve_comp') + async def approve_comp() -> str: + raise Interrupt({'reason': 'manager approval'}) + + response = await ai.generate(model='kitchen-model', prompt='comp the dessert', tools=['approve_comp']) + assert response.finish_reason == FinishReason.INTERRUPTED + + tool, generate = sink.final('approve_comp'), sink.final('generate') + assert tool['attributes']['genkit:state'] == 'error' + assert tool['status'] == {'code': 2} + assert tool['timeEvents'] == {'timeEvent': []} + assert dev_ui_heading(tool) == 'Interrupted' + assert generate['attributes']['genkit:state'] == 'success' + assert generate['timeEvents'] == {'timeEvent': []} + + +@pytest.mark.asyncio +async def test_failure_returned_without_raising_has_status_but_no_exception_event(sink: SnapshotSink) -> None: + """generate boxes a tool failure into its response: status carries the text, but nothing was raised there.""" + ai = Genkit() + scripted_model(ai, [calls_tool('check_stock')]) + + @ai.tool(name='check_stock') + async def check_stock() -> str: + raise RuntimeError('walk-in freezer offline') + + response = await ai.generate(model='kitchen-model', prompt='is the salmon in?', tools=['check_stock']) + assert response.finish_reason == FinishReason.FAILED + + tool, generate = sink.final('check_stock'), sink.final('generate') + assert dev_ui_heading(tool) == 'walk-in freezer offline' + assert generate['attributes']['genkit:state'] == 'error' + assert generate['status']['code'] == 2 + assert 'walk-in freezer offline' in generate['status']['message'] + # The Traces tab's stack box falls back to status.message for this span. + assert generate['timeEvents'] == {'timeEvent': []} diff --git a/packages/genkit/tests/genkit/core/telemetry_test.py b/packages/genkit/tests/genkit/core/telemetry_test.py index 82c8d57a6..8273722b4 100644 --- a/packages/genkit/tests/genkit/core/telemetry_test.py +++ b/packages/genkit/tests/genkit/core/telemetry_test.py @@ -439,13 +439,13 @@ async def flow_fn() -> str: assert inner.span_id != outer.span_id -def _start_collector() -> tuple[HTTPServer, list[str]]: - received: list[str] = [] +def _start_collector() -> tuple[HTTPServer, list[tuple[str, str]]]: + received: list[tuple[str, str]] = [] class Handler(BaseHTTPRequestHandler): def do_POST(self) -> None: # noqa: N802 n = int(self.headers.get('Content-Length', '0')) - received.append(self.rfile.read(n).decode()) + received.append((self.path, self.rfile.read(n).decode())) self.send_response(200) self.end_headers() @@ -457,8 +457,8 @@ def log_message(self, format: str, *args: Any) -> None: return server, received -def _log_posts_with(posts: list[str], text: str) -> list[str]: - return [p for p in list(posts) if 'resourceLogs' in p and text in p] +def _log_posts_with(posts: list[tuple[str, str]], text: str) -> list[str]: + return [body for path, body in list(posts) if path == '/api/otlp' and 'resourceLogs' in body and text in body] def test_reset_instrumentation_stops_dev_ui_log_export(monkeypatch: pytest.MonkeyPatch) -> None: @@ -485,17 +485,51 @@ def test_reset_instrumentation_stops_dev_ui_log_export(monkeypatch: pytest.Monke server.server_close() -def _posted_spans(posts: list[str], name: str) -> list[dict[str, Any]]: +def _posted_spans(posts: list[tuple[str, str]], name: str) -> list[dict[str, Any]]: found: list[dict[str, Any]] = [] - for body in list(posts): - for resource in json.loads(body).get('resourceSpans', []): - for scope in resource['scopeSpans']: - found.extend(span for span in scope['spans'] if span['name'] == name) + for path, body in list(posts): + if path != '/api/traces': + continue + found.extend(span for span in json.loads(body)['spans'].values() if span['displayName'] == name) return found def _attr(span: dict[str, Any], key: str) -> object: - return next(a['value']['stringValue'] for a in span['attributes'] if a['key'] == key) + return span['attributes'][key] + + +def test_dev_ui_spans_post_trace_data_and_logs_post_otlp(monkeypatch: pytest.MonkeyPatch) -> None: + """Spans POST TraceData to /api/traces with the exception event; logs still POST OTLP to /api/otlp.""" + server, posts = _start_collector() + monkeypatch.setenv(GENKIT_ENV, 'dev') + monkeypatch.setenv('GENKIT_TELEMETRY_SERVER', f'http://127.0.0.1:{server.server_address[1]}') + + async def check_allergens(_span: SpanContext) -> None: + get_logger('kitchen').info('checking allergens for order 1042') + raise ValueError('allergen db unavailable') + + try: + Genkit() + with pytest.raises(ValueError, match='allergen db unavailable'): + asyncio.run(run_in_new_span('checkAllergens', check_allergens)) + deadline = time.monotonic() + 5 + while not _log_posts_with(posts, 'order 1042') and time.monotonic() < deadline: + time.sleep(0.05) + reset_instrumentation() + finally: + server.shutdown() + server.server_close() + + assert {path for path, _ in posts} == {'/api/traces', '/api/otlp'} + assert all('resourceSpans' not in body for _, body in posts) + assert _log_posts_with(posts, 'order 1042') + started, ended = _posted_spans(posts, 'checkAllergens') + assert started['endTime'] == 0 + assert started['timeEvents'] == {'timeEvent': []} + assert ended['endTime'] > 0 + (event,) = ended['timeEvents']['timeEvent'] + assert event['annotation']['description'] == 'exception' + assert event['annotation']['attributes']['exception.message'] == 'allergen db unavailable' @pytest.mark.asyncio @@ -548,7 +582,7 @@ class _MemorySink: def __init__(self) -> None: self._spans: list[ActiveSpan] = [] - def export_spans(self, spans: list[ActiveSpan], *, resource_attributes: dict[str, object]) -> None: + def export_spans(self, spans: list[ActiveSpan]) -> None: self._spans.extend(spans) def flush(self) -> None: