From 0040aa59d87a598a5ff464342bc47292f5b4bbc7 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Wed, 11 Nov 2026 22:43:03 -0600 Subject: [PATCH 1/8] fix(py): show error message and traceback on failed spans in the Dev UI Since 0.13.0 the Dev UI poster sent spans as OTLP/JSON to /api/otlp with no events. The telemetry server's OTLP converter drops span events anyway, and the Traces tab reads a non-model span's heading and stack only from its exception event, so failed Python flow and tool spans showed "Error" and no traceback. Spans now POST TraceData to /api/traces, the shape JS and Go send and what Python sent before 0.13. A raised error records exception.type, .message (str(err)) and .stacktrace the way OTel's record_exception formats them, stored as strings so finished spans hold no frames. Interrupts record no event so the tool span still renders as Interrupted. Failures returned without raising keep status but get no event. Logs stay on /api/otlp. --- .../src/genkit/_core/_telemetry/_http.py | 165 +++++--- packages/genkit/tests/genkit/conftest.py | 2 +- .../core/developer_ui_handshake_test.py | 6 +- .../core/telemetry/trace_data_encoder_test.py | 390 ++++++++++++++++++ .../tests/genkit/core/telemetry_test.py | 58 ++- 5 files changed, 548 insertions(+), 73 deletions(-) create mode 100644 packages/genkit/tests/genkit/core/telemetry/trace_data_encoder_test.py diff --git a/packages/genkit/src/genkit/_core/_telemetry/_http.py b/packages/genkit/src/genkit/_core/_telemetry/_http.py index 86219f416..96ae4049a 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,10 +27,12 @@ import asyncio import contextlib import json +import math import os import secrets import threading import time +import traceback import urllib.request from collections.abc import Mapping from contextvars import ContextVar @@ -65,6 +70,8 @@ # 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 +# Same scope the JS and Go posters stamp, and what Python sent before 0.13. +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,96 @@ 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'] = ''.join(traceback.format_exception(cls, exc, exc.__traceback__)) + return attrs + + +def nanos_to_millis(nanos: int) -> float: + return nanos / 1_000_000 -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_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_span(span: ActiveSpan, *, resource_attributes: dict[str, object]) -> dict[str, object]: +def encode_span(span: ActiveSpan) -> dict[str, object]: + """One ``SpanData`` in the shape the collector's ``/api/traces`` schema takes. + + 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 collector_otlp_url(server: str) -> str: - return urljoin(server.rstrip('/') + '/', 'api/otlp') +def encode_traces(spans: list[ActiveSpan]) -> list[dict[str, object]]: + """One ``TraceData`` per trace id in ``spans``. + + 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. + """ + traces: dict[str, dict[str, object]] = {} + spans_by_trace: dict[str, dict[str, object]] = {} + for span in spans: + if span.trace_id not in traces: + spans_by_trace[span.trace_id] = {} + traces[span.trace_id] = {'traceId': span.trace_id, 'spans': spans_by_trace[span.trace_id]} + encoded = encode_span(span) + spans_by_trace[span.trace_id][span.span_id] = encoded + if span.parent_span_id is None: + trace = traces[span.trace_id] + trace['displayName'] = span.name + trace['startTime'] = encoded['startTime'] + if span.end_time_unix_nano: + trace['endTime'] = encoded['endTime'] + return list(traces.values()) + + +def collector_traces_url(server: str) -> str: + return urljoin(server.rstrip('/') + '/', 'api/traces') def post_json(*, url: str, body: str) -> None: @@ -204,7 +254,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 +263,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 trace in encode_traces(spans): + try: + self.queue.put_nowait(json.dumps(trace)) + except Full: + logger.debug('Developer UI trace export queue is full; dropping spans') def run_worker(self) -> None: while True: @@ -252,14 +304,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 +326,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 +342,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) @@ -309,12 +357,15 @@ async def run_in_new_span( 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: 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 +430,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..287287349 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: 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..603116bad --- /dev/null +++ b/packages/genkit/tests/genkit/core/telemetry/trace_data_encoder_test.py @@ -0,0 +1,390 @@ +# 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 json +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_traces, +) +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(trace)) for trace in encode_traces(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(sink: SnapshotSink) -> 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) + + reset_instrumentation() + configure_instrumentation(DirectHttpInstrumentation(HoldingSink())) # type: ignore[arg-type] + + async def charge_card(_span: SpanContext) -> None: + raise RuntimeError('card declined') + + with pytest.raises(RuntimeError): + await run_in_new_span('chargeCard', charge_card) + + 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: From 92d894ccc0a57bc454423bd6bea848494eb4d9af Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Wed, 11 Nov 2026 22:51:48 -0600 Subject: [PATCH 2/8] chore(py): tighten INSTRUMENTATION_LIBRARY comment --- packages/genkit/src/genkit/_core/_telemetry/_http.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/genkit/src/genkit/_core/_telemetry/_http.py b/packages/genkit/src/genkit/_core/_telemetry/_http.py index 96ae4049a..83ece197b 100644 --- a/packages/genkit/src/genkit/_core/_telemetry/_http.py +++ b/packages/genkit/src/genkit/_core/_telemetry/_http.py @@ -70,7 +70,7 @@ # 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 -# Same scope the JS and Go posters stamp, and what Python sent before 0.13. +# instrumentationLibrary on every posted span; JS and Go send the same value. INSTRUMENTATION_LIBRARY = {'name': 'genkit-tracer', 'version': 'v1'} From b1b0f5ae5535f9e9aae2087f7b48971f62876143 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Wed, 11 Nov 2026 22:52:35 -0600 Subject: [PATCH 3/8] chore(py): clarify INSTRUMENTATION_LIBRARY is a cross-SDK span field --- packages/genkit/src/genkit/_core/_telemetry/_http.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/genkit/src/genkit/_core/_telemetry/_http.py b/packages/genkit/src/genkit/_core/_telemetry/_http.py index 83ece197b..34609ceb1 100644 --- a/packages/genkit/src/genkit/_core/_telemetry/_http.py +++ b/packages/genkit/src/genkit/_core/_telemetry/_http.py @@ -70,7 +70,8 @@ # 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 -# instrumentationLibrary on every posted span; JS and Go send the same value. +# Cross-SDK constant for each span's ``instrumentationLibrary`` field in the +# /api/traces body (a span field, not an attribute). Same value as JS and Go. INSTRUMENTATION_LIBRARY = {'name': 'genkit-tracer', 'version': 'v1'} From 4ad54e3c6f9f97a38d4d7722818ef78944e82bea Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Wed, 11 Nov 2026 22:54:03 -0600 Subject: [PATCH 4/8] chore(py): trim INSTRUMENTATION_LIBRARY comment --- packages/genkit/src/genkit/_core/_telemetry/_http.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/genkit/src/genkit/_core/_telemetry/_http.py b/packages/genkit/src/genkit/_core/_telemetry/_http.py index 34609ceb1..49a7101a4 100644 --- a/packages/genkit/src/genkit/_core/_telemetry/_http.py +++ b/packages/genkit/src/genkit/_core/_telemetry/_http.py @@ -70,8 +70,8 @@ # 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 constant for each span's ``instrumentationLibrary`` field in the -# /api/traces body (a span field, not an attribute). Same value as JS and Go. +# Cross-SDK value for each span's ``instrumentationLibrary`` field in the +# /api/traces body. INSTRUMENTATION_LIBRARY = {'name': 'genkit-tracer', 'version': 'v1'} From 997962f894eee9e8d455896998021b03dc0f7317 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Wed, 11 Nov 2026 23:06:15 -0600 Subject: [PATCH 5/8] test(py): drop resource_attributes from Dev UI sink fakes merged from main --- .../genkit/tests/genkit/core/developer_ui_handshake_test.py | 2 +- .../genkit/tests/genkit/core/endpoints/reflection_test.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) 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 287287349..c95ccddeb 100644 --- a/packages/genkit/tests/genkit/core/developer_ui_handshake_test.py +++ b/packages/genkit/tests/genkit/core/developer_ui_handshake_test.py @@ -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: From a5ed000d183d2afaf0d173f97479aac10e9f807c Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Wed, 11 Nov 2026 23:55:36 -0600 Subject: [PATCH 6/8] fix(py): title spans that fail without raising with their message A boxed generate or a failed dotprompt returns instead of raising, so its span had status text but no exception event, and the Dev UI Traces tab titled it "Error". set_state('error', message=...) now adds an exception event with that message. The boxed response holds no traceback, so the event has no stack; the span that raised still has the full one. A raised exception replaces it. --- .../src/genkit/_core/_telemetry/_http.py | 6 ++ .../tests/genkit/ai/prompt_trace_test.py | 2 + .../core/telemetry/trace_data_encoder_test.py | 57 +++++++++++++++++-- 3 files changed, 61 insertions(+), 4 deletions(-) diff --git a/packages/genkit/src/genkit/_core/_telemetry/_http.py b/packages/genkit/src/genkit/_core/_telemetry/_http.py index 49a7101a4..130d574f9 100644 --- a/packages/genkit/src/genkit/_core/_telemetry/_http.py +++ b/packages/genkit/src/genkit/_core/_telemetry/_http.py @@ -132,6 +132,12 @@ def set_state(self, state: Literal['success', 'error'], *, message: str | None = if message: self._span.attributes[Attr.ERROR] = message self._span.status_message = message + # A span that fails without raising (a boxed generate, a + # dotprompt) has no exception event, and the Traces tab titles + # it "Error". The boxed response holds no traceback, so this + # one carries the message only; the span that raised has the stack. + if self._span.exception is None: + self._span.exception = {'exception.message': message} if not self._span.has_failed_child: self._span.attributes[Attr.IS_FAILURE_SOURCE] = True note_child_failed(self._span) diff --git a/packages/genkit/tests/genkit/ai/prompt_trace_test.py b/packages/genkit/tests/genkit/ai/prompt_trace_test.py index 99e44744b..df6d90be7 100644 --- a/packages/genkit/tests/genkit/ai/prompt_trace_test.py +++ b/packages/genkit/tests/genkit/ai/prompt_trace_test.py @@ -198,6 +198,8 @@ async def prompt_flow(name: str) -> str: assert prompt_span.status_code == 2 assert [s.name for s in spans if s.attributes.get(Attr.IS_FAILURE_SOURCE)] == [MODEL] assert '"finishReason":"failed"' in str(prompt_span.attributes[Attr.OUTPUT]) + # The Traces tab titles the span from this, not "Error". + assert prompt_span.exception == {'exception.message': 'fake model failure'} @pytest.mark.asyncio 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 index 603116bad..946966206 100644 --- a/packages/genkit/tests/genkit/core/telemetry/trace_data_encoder_test.py +++ b/packages/genkit/tests/genkit/core/telemetry/trace_data_encoder_test.py @@ -303,6 +303,54 @@ async def wait_for_oven(_span: SpanContext) -> None: assert 'TimeoutError' in attrs['exception.stacktrace'] +@pytest.mark.asyncio +async def test_span_failed_without_raising_titles_with_the_message(sink: SnapshotSink) -> None: + """set_state('error', message=...) adds an exception event, so the heading is the message, not "Error".""" + + async def plate_order(span: SpanContext) -> str: + span.set_state('error', message='allergen db unavailable') + return 'returned failed' + + await run_in_new_span('plateOrder', plate_order) + + span = sink.final('plateOrder') + assert exception_event(span) == {'exception.message': 'allergen db unavailable'} + assert span['status'] == {'code': 2, 'message': 'allergen db unavailable'} + assert dev_ui_heading(span) == 'allergen db unavailable' + + +@pytest.mark.asyncio +async def test_raised_error_replaces_the_set_state_event(sink: SnapshotSink) -> None: + """A body that marks itself failed and then raises shows the raised error, with its stack.""" + + async def plate_order(span: SpanContext) -> None: + span.set_state('error', message='plating failed') + raise ValueError('oven offline') + + with pytest.raises(ValueError): + await run_in_new_span('plateOrder', plate_order) + + span = sink.final('plateOrder') + (event,) = span['timeEvents']['timeEvent'] + attrs = event['annotation']['attributes'] + assert (attrs['exception.type'], attrs['exception.message']) == ('ValueError', 'oven offline') + assert 'in plate_order' in attrs['exception.stacktrace'] + + +@pytest.mark.asyncio +async def test_set_state_without_message_adds_no_event(sink: SnapshotSink) -> None: + """With no message there's nothing to title the span with; it stays "Error".""" + + async def plate_order(span: SpanContext) -> None: + span.set_state('error') + + await run_in_new_span('plateOrder', plate_order) + + span = sink.final('plateOrder') + assert exception_event(span) is None + assert dev_ui_heading(span) == 'Error' + + @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.""" @@ -369,8 +417,8 @@ async def approve_comp() -> str: @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.""" +async def test_failure_returned_without_raising_titles_generate_with_the_message(sink: SnapshotSink) -> None: + """generate boxes a tool failure into its response; its span still titles with the tool's message.""" ai = Genkit() scripted_model(ai, [calls_tool('check_stock')]) @@ -386,5 +434,6 @@ async def check_stock() -> str: 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': []} + assert dev_ui_heading(generate) == 'walk-in freezer offline' + # Nothing raised in generate, so no stack here; the tool span has it. + assert exception_event(generate) == {'exception.message': generate['status']['message']} From e3d8bcaf9b6ad3c842c87ff03af03a5e61b920c9 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 12 Nov 2026 00:02:00 -0600 Subject: [PATCH 7/8] fix(py): lead Dev UI stacks with the user's frame, tighten error text - Stack traces on spans and in the runner drop the leading frames under genkit/_core and genkit/_ai, per traceback in the cause chain, so a failed tool reads from the tool's own line instead of 6-10 runtime frames. A traceback that is all Genkit frames is kept whole. - The runner heading for a GenkitError is str(error), the same `STATUS: message[: cause]` as the span's status.message and JS's `STATUS: message`, instead of `message: repr(cause)`. - GenkitError skips the cause suffix when the cause's own .message is the message. A google-genai APIError's str() is that message again in a dict repr. - Config bound errors say "got 99.0" once; the bounds message already names the value, so the config check doesn't append the input. --- .../tests/models/googlegenai_gemini_test.py | 16 +++ .../genkit-mcp/tests/mcp_connection_test.py | 2 +- packages/genkit/src/genkit/_core/_error.py | 46 ++++++- .../genkit/src/genkit/_core/_reflection.py | 5 +- .../genkit/src/genkit/_core/_reflection_v2.py | 4 +- .../src/genkit/_core/_telemetry/_http.py | 5 +- .../tests/genkit/ai/config_pipeline_test.py | 22 +++- .../genkit/core/endpoints/reflection_test.py | 7 +- .../genkit/tests/genkit/core/error_test.py | 120 +++++++++++++++++- .../tests/genkit/core/reflection_v2_test.py | 4 +- .../core/telemetry/trace_data_encoder_test.py | 20 +++ 11 files changed, 234 insertions(+), 17 deletions(-) diff --git a/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py b/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py index 02af6b0dc..4093f80c0 100644 --- a/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py +++ b/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py @@ -2889,6 +2889,22 @@ async def test_unmapped_4xx_is_unknown_genkit_error(mocker: MockerFixture, code: assert error.message == 'Request payload too large' +@pytest.mark.asyncio +async def test_api_error_text_names_the_message_once(mocker: MockerFixture) -> None: + """str() of the error is `STATUS: message`, not the message plus the SDK's dict repr of it.""" + body = { + 'error': { + 'code': 404, + 'message': 'models/gemini-0.9-menu is not found for API version v1beta', + 'status': 'NOT_FOUND', + } + } + + error = await _generate_failure(mocker, APIError(404, body)) + + assert str(error) == 'NOT_FOUND: models/gemini-0.9-menu is not found for API version v1beta' + + @pytest.mark.asyncio async def test_429_retry_after_header_sets_retry_delay(mocker: MockerFixture) -> None: """A Gemini 429 with a Retry-After header tells retry how long to wait.""" diff --git a/packages/genkit-mcp/tests/mcp_connection_test.py b/packages/genkit-mcp/tests/mcp_connection_test.py index b62806fd9..ced317ef5 100644 --- a/packages/genkit-mcp/tests/mcp_connection_test.py +++ b/packages/genkit-mcp/tests/mcp_connection_test.py @@ -1068,7 +1068,7 @@ async def test_startup_failure_is_terminal_and_names_the_server_and_why(tmp_path assert isinstance(cause, OSError) assert attached_cause(failure.value) is cause assert str(cause) in str(failure.value) - assert repr(cause) in get_reflection_json(failure.value).message + assert get_reflection_json(failure.value).message == str(failure.value) assert connection._state is _ConnectionState.FAILED with pytest.raises(_ConnectionFailedError, match='failed'): diff --git a/packages/genkit/src/genkit/_core/_error.py b/packages/genkit/src/genkit/_core/_error.py index 48516ad30..3fd8bfb9c 100644 --- a/packages/genkit/src/genkit/_core/_error.py +++ b/packages/genkit/src/genkit/_core/_error.py @@ -20,8 +20,10 @@ import copy import importlib import math +import os import reprlib import time +import traceback from collections.abc import Mapping, Sequence from dataclasses import dataclass from email.utils import parsedate_to_datetime @@ -482,8 +484,9 @@ def validation_problem(err: ErrorDetails, *, show_input: bool) -> str: """Pydantic's message for one error, plus ``, got `` when the value is worth printing. For a missing field the input is the whole parent object, which says nothing new. + A ``common_field_bounds`` message already ends in ``got ``. """ - if err['type'] == 'missing' or not show_input: + if err['type'] in ('missing', 'common_field_bounds') or not show_input: return err['msg'] return f'{err["msg"]}, got {_value_preview.repr(err["input"])}' @@ -559,8 +562,12 @@ def __init__( else: # Skip a cause whose text is empty or already in the message, so a # bare TimeoutError() adds no dangling ': ' and nothing repeats. + # Also skip one whose own .message is ours: provider_error takes a + # google-genai APIError's message, and str() of that APIError is + # the same message again inside a dict repr. cause_text = str(cause) if cause is not None else '' - cause_suffix = f': {cause_text}' if cause_text and cause_text not in message else '' + repeats = cause_text in message or getattr(cause, 'message', None) == message + cause_suffix = f': {cause_text}' if cause_text and not repeats else '' super().__init__(f'{source_prefix}{self.status}: {message}{cause_suffix}') self.message: str = message @@ -961,7 +968,9 @@ def get_reflection_json(error: object, *, trace_id: str | None = None) -> Reflec ref = ReflectionError( details=ReflectionErrorDetails(**raw_details), code=StatusCodes[error.status].value, - message=f'{error.message}: {repr(cause)}' if cause else error.message, + # Same text as the span's status.message, so the runner and the + # trace agree: `STATUS: message`, plus the cause when it adds anything. + message=str(error), ) else: ref = ReflectionError( @@ -1034,3 +1043,34 @@ 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 + + +# The action runtime, telemetry and generate loop. Every action call enters +# through 6-10 frames here before it reaches the user's function. +_GENKIT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +_INTERNAL_DIRS = tuple(os.path.join(_GENKIT_DIR, name) + os.sep for name in ('_core', '_ai')) + + +def format_exception_stack(exc: BaseException) -> str: + """``traceback.format_exception`` text, minus the Genkit frames that lead into user code. + + Python prints the outermost frame first, so a failed tool reads + ``run_in_new_span``, ``_run_with_span``, ``_invoke`` ... before the line + that raised. Each traceback in the cause/context chain drops its leading + frames under ``genkit/_core`` and ``genkit/_ai``; one that is all Genkit + frames is kept whole, so a bug in Genkit still shows where it happened. + """ + top = traceback.TracebackException.from_exception(exc) + pending: list[traceback.TracebackException] = [top] + seen: set[int] = set() + while pending: + te = pending.pop() + if id(te) in seen: + continue + seen.add(id(te)) + frames = list(te.stack) + first_user = next((i for i, f in enumerate(frames) if not f.filename.startswith(_INTERNAL_DIRS)), 0) + if first_user: + te.stack = traceback.StackSummary.from_list(frames[first_user:]) + pending.extend(t for t in (te.__cause__, te.__context__) if t is not None) + return ''.join(top.format()) diff --git a/packages/genkit/src/genkit/_core/_reflection.py b/packages/genkit/src/genkit/_core/_reflection.py index 2ca30fc0d..b104bcae6 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_stack, 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_stack(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..30a0b60a2 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_stack, 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_stack(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 130d574f9..e1e707f5d 100644 --- a/packages/genkit/src/genkit/_core/_telemetry/_http.py +++ b/packages/genkit/src/genkit/_core/_telemetry/_http.py @@ -32,7 +32,6 @@ import secrets import threading import time -import traceback import urllib.request from collections.abc import Mapping from contextvars import ContextVar @@ -42,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_stack from .._logger import get_logger from .._reflection_config import reflection_enabled from ._attrs import Attr, State, metadata_key @@ -167,7 +166,7 @@ def exception_attributes(exc: BaseException) -> dict[str, str]: message = str(exc) if message: attrs['exception.message'] = message - attrs['exception.stacktrace'] = ''.join(traceback.format_exception(cls, exc, exc.__traceback__)) + attrs['exception.stacktrace'] = format_exception_stack(exc) return attrs diff --git a/packages/genkit/tests/genkit/ai/config_pipeline_test.py b/packages/genkit/tests/genkit/ai/config_pipeline_test.py index f06396d1f..b773f8598 100644 --- a/packages/genkit/tests/genkit/ai/config_pipeline_test.py +++ b/packages/genkit/tests/genkit/ai/config_pipeline_test.py @@ -1029,5 +1029,25 @@ async def crm_search(request: EmbedRequest[ChefConfig]) -> EmbedResponse: await call() assert str(err.value) == f'INVALID_ARGUMENT: {name}: {problem}' assert isinstance(err.value.__cause__, ValidationError) - assert get_reflection_json(err.value).message == err.value.message + assert get_reflection_json(err.value).message == str(err.value) assert err.value.details['errors'][0]['loc'] == ['temperature'] + + +class _KitchenConfig(ModelConfig): + common_field_bounds = {'temperature': (0.0, 2.0)} + + +@pytest.mark.asyncio +async def test_config_out_of_bounds_says_got_once() -> None: + """The bounds message already names the value; the config check doesn't append it again.""" + ai = Genkit() + + async def chef(request: ModelRequest[_KitchenConfig], ctx: ActionRunContext) -> ModelResponse: + return _ok() + + ai.define_model(name='chef', fn=chef, config_schema=_KitchenConfig) + + with pytest.raises(GenkitError) as err: + await ai.generate(model='chef', prompt='plan the tasting menu', config={'temperature': 99}) + + assert err.value.message == "chef: config 'temperature': temperature must be between 0.0 and 2.0, got 99.0" diff --git a/packages/genkit/tests/genkit/core/endpoints/reflection_test.py b/packages/genkit/tests/genkit/core/endpoints/reflection_test.py index 4845a06d6..de5904a23 100644 --- a/packages/genkit/tests/genkit/core/endpoints/reflection_test.py +++ b/packages/genkit/tests/genkit/core/endpoints/reflection_test.py @@ -616,7 +616,8 @@ async def order(order_id: str) -> str: response = await client.post('/api/runAction', json={'key': '/flow/order', 'input': '99'}) error = response.json()['error'] - assert error['message'] == 'no order 99' + # Same `STATUS: message` the trace shows, and what JS sends. + assert error['message'] == 'NOT_FOUND: no order 99' assert error['code'] == 5 assert error['details']['traceId'] == response.headers['x-genkit-trace-id'] @@ -726,6 +727,10 @@ async def check_allergens(dish: str) -> str: assert 'Traceback (most recent call last)' in stack assert 'check_allergens' in stack assert 'ValueError: unknown allergen profile for Tartine' in stack + # The flow's own line comes first; the reflection server and action + # runtime frames that lead into it are dropped. + first_frame = next(line for line in stack.splitlines() if line.strip().startswith('File ')) + assert __file__ in first_frame and 'in check_allergens' in first_frame @pytest.mark.asyncio diff --git a/packages/genkit/tests/genkit/core/error_test.py b/packages/genkit/tests/genkit/core/error_test.py index 77895b8a8..e99dc9256 100644 --- a/packages/genkit/tests/genkit/core/error_test.py +++ b/packages/genkit/tests/genkit/core/error_test.py @@ -17,6 +17,7 @@ """Unit tests for the error module.""" import json +import os from typing import Any, Literal from unittest.mock import MagicMock @@ -32,6 +33,7 @@ GenkitError, PublicError, ReflectionError, + format_exception_stack, format_validation_error, get_error_stack, get_reflection_json, @@ -241,7 +243,7 @@ def test_genkit_error_to_json() -> None: serializable = get_reflection_json(error) assert isinstance(serializable, ReflectionError) assert serializable.code == 5 - assert serializable.message == 'Resource not found' + assert serializable.message == 'NOT_FOUND: Resource not found' assert serializable.details is not None assert serializable.details.model_dump()['id'] == 123 @@ -773,3 +775,119 @@ def test_genkit_error_with_empty_validation_error_has_no_trailing_colon() -> Non ) assert str(error) == 'INVALID_ARGUMENT: title missing' + + +def test_reflection_message_matches_the_span_status_text() -> None: + """The runner heading is str(error), the same `STATUS: message: cause` the trace shows, not the cause's repr.""" + error = GenkitError( + status='UNAVAILABLE', + message='pricing service unavailable for ribeye', + cause=ConnectionError('pricing upstream timed out'), + ) + + assert get_reflection_json(error).message == ( + 'UNAVAILABLE: pricing service unavailable for ribeye: pricing upstream timed out' + ) + + +class _SdkError(Exception): + """Shaped like google-genai's APIError: .message is the text, str() wraps it in a dict repr.""" + + def __init__(self, message: str) -> None: + super().__init__(f"404 NOT_FOUND. {{'error': {{'message': {message!r}}}}}") + self.message = message + + +def test_cause_whose_message_is_ours_is_not_appended() -> None: + """A provider error built from the SDK error's own message doesn't repeat it as a dict repr.""" + cause = _SdkError('models/gemini-0.9-menu is not found') + + error = GenkitError(status='NOT_FOUND', message=cause.message, cause=cause) + + assert str(error) == 'NOT_FOUND: models/gemini-0.9-menu is not found' + assert error.__cause__ is cause + + +def test_cause_with_a_different_message_is_still_appended() -> None: + """Only an exact repeat is dropped; a cause that says something new still shows.""" + error = GenkitError(status='UNAVAILABLE', message='menu lookup failed', cause=_SdkError('quota exhausted')) + + assert str(error).startswith('UNAVAILABLE: menu lookup failed: 404 NOT_FOUND.') + + +# Code compiled under genkit/_core stands in for the action runtime that wraps +# every user function, so the test controls which frames count as internal. +_FAKE_RUNTIME = os.path.join(os.path.dirname(error_mod.__file__), '_fake_runtime.py') + + +def _runtime(source: str) -> dict[str, Any]: + scope: dict[str, Any] = {} + exec(compile(source, _FAKE_RUNTIME, 'exec'), scope) # noqa: S102 - test-only stand-in for Genkit frames + return scope + + +def _check_allergens(dish: str) -> str: + raise ValueError(f'allergen db unavailable for {dish}') + + +def _frames(stack: str) -> list[str]: + return [line.strip() for line in stack.splitlines() if line.strip().startswith('File ')] + + +def test_stack_drops_leading_genkit_frames_so_the_user_frame_comes_first() -> None: + """A tool failure's stack starts at the tool, not at run_in_new_span.""" + runtime = _runtime( + 'def run_action(fn, arg):\n' + ' try:\n' + ' return invoke(fn, arg)\n' + ' except Exception as e:\n' + ' return e\n' + 'def invoke(fn, arg):\n' + ' return fn(arg)\n' + ) + + exc = runtime['run_action'](_check_allergens, 'pad thai') + stack = format_exception_stack(exc) + + frames = _frames(stack) + assert len(frames) == 1 + assert __file__ in frames[0] and 'in _check_allergens' in frames[0] + assert stack.rstrip().endswith('ValueError: allergen db unavailable for pad thai') + + +def test_stack_keeps_every_frame_when_all_are_genkit() -> None: + """A failure inside Genkit itself keeps its frames, so the bug still has a location.""" + runtime = _runtime( + 'def run_action():\n' + ' try:\n' + ' return resolve()\n' + ' except Exception as e:\n' + ' return e\n' + 'def resolve():\n' + ' raise KeyError("model")\n' + ) + + stack = format_exception_stack(runtime['run_action']()) + + assert [f.split(', in ')[-1] for f in _frames(stack)] == ['run_action', 'resolve'] + + +def test_stack_trims_each_traceback_in_the_cause_chain() -> None: + """Both the cause and the wrapping error lose their leading Genkit frames.""" + + def surge_pricing(dish: str) -> str: + try: + _check_allergens(dish) + except ValueError as e: + raise GenkitError(status='UNAVAILABLE', message='pricing unavailable', cause=e) from e + return dish + + runtime = _runtime( + 'def run_action(fn, arg):\n try:\n return fn(arg)\n except Exception as e:\n return e\n' + ) + + stack = format_exception_stack(runtime['run_action'](surge_pricing, 'ribeye')) + + assert _FAKE_RUNTIME not in stack + assert 'The above exception was the direct cause of the following exception' in stack + assert [f.split(', in ')[-1] for f in _frames(stack)] == ['surge_pricing', '_check_allergens', 'surge_pricing'] diff --git a/packages/genkit/tests/genkit/core/reflection_v2_test.py b/packages/genkit/tests/genkit/core/reflection_v2_test.py index 6dda3c8bb..c151b5a58 100644 --- a/packages/genkit/tests/genkit/core/reflection_v2_test.py +++ b/packages/genkit/tests/genkit/core/reflection_v2_test.py @@ -584,7 +584,7 @@ async def refund_order(order_id: str) -> str: assert isinstance(err, dict) assert err.get('data', {}).get('code') == StatusCodes.INTERNAL.value # Same wording as every other boundary, not Interrupt's empty str(). - assert str(err.get('message')).startswith('Interrupt raised outside a tool') + assert str(err.get('message')).startswith('INTERNAL: Interrupt raised outside a tool') finally: await _stop_client(client, task) @@ -1012,7 +1012,7 @@ async def refund_order(order_id: str) -> str: assert body is not None error = json.loads(body)['error'] assert error['code'] == StatusCodes.INTERNAL.value - assert error['message'].startswith('Interrupt raised outside a tool') + assert error['message'].startswith('INTERNAL: Interrupt raised outside a tool') assert runner.queue.get_nowait() is 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 index 946966206..d698df5b4 100644 --- a/packages/genkit/tests/genkit/core/telemetry/trace_data_encoder_test.py +++ b/packages/genkit/tests/genkit/core/telemetry/trace_data_encoder_test.py @@ -267,6 +267,26 @@ async def take_order(dish: str) -> str: assert 'genkit:isFailureSource' not in flow['attributes'] +@pytest.mark.asyncio +async def test_tool_stack_starts_at_the_user_frame(sink: SnapshotSink) -> None: + """The stack box leads with the tool's own line, not the action runtime's frames.""" + ai = Genkit() + + @ai.tool() + async def check_allergens(dish: str) -> str: + raise ValueError('allergen db unavailable') + + with pytest.raises(ValueError): + await check_allergens('pad thai') + + attrs = exception_event(sink.final('check_allergens')) + assert attrs is not None + frames = [line for line in attrs['exception.stacktrace'].splitlines() if line.strip().startswith('File ')] + assert frames, attrs['exception.stacktrace'] + assert __file__ in frames[0] and 'in check_allergens' in frames[0] + assert 'run_in_new_span' not in attrs['exception.stacktrace'] + + @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.""" From 8458ca5d7b0dab9a301e67482f954f4b771698f2 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 12 Nov 2026 17:48:51 -0600 Subject: [PATCH 8/8] style: format _http.py --- packages/genkit/src/genkit/_core/_telemetry/_http.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/genkit/src/genkit/_core/_telemetry/_http.py b/packages/genkit/src/genkit/_core/_telemetry/_http.py index 99036ae4d..40415ec10 100644 --- a/packages/genkit/src/genkit/_core/_telemetry/_http.py +++ b/packages/genkit/src/genkit/_core/_telemetry/_http.py @@ -216,6 +216,8 @@ def encode_span(span: ActiveSpan) -> dict[str, object]: if span.parent_span_id: body['parentSpanId'] = span.parent_span_id return body + + def encode_trace(span: ActiveSpan) -> dict[str, object]: """One ``TraceData`` payload for a single span in the collector's ``/api/traces`` schema. @@ -234,6 +236,8 @@ def encode_trace(span: ActiveSpan) -> dict[str, object]: if span.end_time_unix_nano: trace['endTime'] = encoded['endTime'] return trace + + def collector_traces_url(server: str) -> str: return urljoin(server.rstrip('/') + '/', 'api/traces')