Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
2 changes: 1 addition & 1 deletion packages/genkit-mcp/tests/mcp_connection_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'):
Expand Down
46 changes: 40 additions & 6 deletions packages/genkit/src/genkit/_core/_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import copy
import importlib
import math
import os
import reprlib
import time
import traceback
Expand Down Expand Up @@ -483,8 +484,9 @@ def validation_problem(err: ErrorDetails, *, show_input: bool) -> str:
"""Pydantic's message for one error, plus ``, got <value>`` 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 <value>``.
"""
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"])}'

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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())
4 changes: 2 additions & 2 deletions packages/genkit/src/genkit/_core/_reflection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)})

Expand Down
4 changes: 2 additions & 2 deletions packages/genkit/src/genkit/_core/_reflection_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
ReflectionError,
ReflectionErrorDetails,
StatusCodes,
format_exception_traceback,
format_exception_stack,
get_reflection_json,
interrupt_escape_error,
)
Expand Down Expand Up @@ -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,
Expand Down
10 changes: 8 additions & 2 deletions packages/genkit/src/genkit/_core/_telemetry/_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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


Expand Down
22 changes: 21 additions & 1 deletion packages/genkit/tests/genkit/ai/config_pipeline_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
2 changes: 2 additions & 0 deletions packages/genkit/tests/genkit/ai/prompt_trace_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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']

Expand Down Expand Up @@ -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
Expand Down
120 changes: 119 additions & 1 deletion packages/genkit/tests/genkit/core/error_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"""Unit tests for the error module."""

import json
import os
from typing import Any, Literal
from unittest.mock import MagicMock

Expand All @@ -32,6 +33,7 @@
GenkitError,
PublicError,
ReflectionError,
format_exception_stack,
format_validation_error,
get_error_stack,
get_reflection_json,
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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']
4 changes: 2 additions & 2 deletions packages/genkit/tests/genkit/core/reflection_v2_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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


Expand Down
Loading
Loading