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 09f772556..ee484be5f 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 4edcfddb0..3fd8bfb9c 100644 --- a/packages/genkit/src/genkit/_core/_error.py +++ b/packages/genkit/src/genkit/_core/_error.py @@ -20,6 +20,7 @@ import copy import importlib import math +import os import reprlib import time import traceback @@ -483,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"])}' @@ -560,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 @@ -962,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( @@ -1037,6 +1045,32 @@ def get_error_stack(error: object) -> str | None: 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__)) +# 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 699b22243..b104bcae6 100644 --- a/packages/genkit/src/genkit/_core/_reflection.py +++ b/packages/genkit/src/genkit/_core/_reflection.py @@ -42,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, format_exception_traceback, 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 @@ -186,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 = format_exception_traceback(e) + 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 4468e1df4..30a0b60a2 100644 --- a/packages/genkit/src/genkit/_core/_reflection_v2.py +++ b/packages/genkit/src/genkit/_core/_reflection_v2.py @@ -49,7 +49,7 @@ ReflectionError, ReflectionErrorDetails, StatusCodes, - format_exception_traceback, + 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 = format_exception_traceback(exc) + 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 2672ec185..40415ec10 100644 --- a/packages/genkit/src/genkit/_core/_telemetry/_http.py +++ b/packages/genkit/src/genkit/_core/_telemetry/_http.py @@ -41,7 +41,7 @@ from urllib.parse import urljoin, urlparse from .._environment import is_dev_environment -from .._error import GenkitError, Interrupt, _StreamingCallbackError, format_exception_traceback +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 @@ -131,6 +131,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) @@ -160,7 +166,7 @@ def exception_attributes(exc: BaseException) -> dict[str, str]: message = str(exc) if message: attrs['exception.message'] = message - attrs['exception.stacktrace'] = format_exception_traceback(exc) + 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/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/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 0fa679b48..1351c37b2 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 @@ -269,6 +269,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.""" @@ -305,6 +325,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.""" @@ -389,8 +457,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')]) @@ -406,5 +474,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']}