Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -455,10 +455,10 @@ def set_metadata(self, metadata: Mapping[str, object]) -> None:
# Keep ad-hoc metadata out of the reserved gen_ai.* namespace.
self._span.set_attribute(f'genkit:metadata:{key}', value_string)

def set_state(self, state: str) -> None:
def set_state(self, state: str, *, message: str | None = None) -> None:
self._span.set_attribute('genkit:state', state)
if state == 'error':
self._span.set_status(StatusCode.ERROR)
self._span.set_status(StatusCode.ERROR, message or None)


def _content_capturing_mode_from_env() -> ContentCapturingMode:
Expand Down
38 changes: 38 additions & 0 deletions packages/genkit-otel/tests/genai_instrumentation_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1163,3 +1163,41 @@ async def body(span=None):
assert span is not None
assert harness.attr(span, 'genkit:metadata:at') == '"2026-11-10T00:00:00Z"'
assert harness.attr(span, 'genkit:metadata:raw') == '"_w=="'


@pytest.mark.asyncio
async def test_failed_generate_sets_otel_span_status_description(harness) -> None:
"""When a tool raises inside ai.generate, the OTel generate span gets StatusCode.ERROR and the failure text."""
from genkit import Genkit
from genkit.model import ModelContext
from genkit.telemetry import configure_instrumentation, reset_instrumentation

reset_instrumentation()
try:
configure_instrumentation(harness.instrumentation(emit_tool_spans=True))
ai = Genkit()

@ai.tool(name='check_stock')
async def check_stock() -> str:
raise RuntimeError('fridge offline')

async def calls_tool(_req: ModelRequest, _ctx: ModelContext) -> ModelResponse:
return ModelResponse(
finish_reason=FinishReason.STOP,
message=Message(
role=Role.MODEL,
content=[Part.from_tool_request('check_stock', input={}, ref='r1')],
),
)

ai.define_model(name='googleai/gemini-flash-latest', fn=calls_tool)

resp = await ai.generate(model='googleai/gemini-flash-latest', prompt='Check salmon', tools=['check_stock'])
assert resp.finish_reason == FinishReason.FAILED

gen_span = harness.span_named('generate')
assert gen_span is not None
assert gen_span.status.status_code == StatusCode.ERROR
assert gen_span.status.description == 'fridge offline'
finally:
reset_instrumentation()
6 changes: 5 additions & 1 deletion packages/genkit/src/genkit/_ai/_agents/_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
SessionSnapshot,
SessionState,
)
from genkit._core._telemetry._http import mark_already_sourced
from genkit._core._telemetry._instrumentation import SpanContext, run_in_new_span
from genkit._core._typing import (
AgentFinishReason,
Expand Down Expand Up @@ -1166,16 +1167,19 @@ def on_chunk(chunk: ModelResponseChunk) -> None:
# Bad JSON is not a dead turn — generate already kept the model text.
if response.error is not None and response.error.reason is not ErrorReason.INVALID_OUTPUT:
if is_public_failure(response.error):
raise PublicError(
public_err = PublicError(
response.error.status or 'INTERNAL',
response.error.message,
details=response.error.details,
)
mark_already_sourced(public_err)
raise public_err
err = GenkitError(
message=response.error.message,
status=response.error.status,
details=response.error.details,
)
mark_already_sourced(err)
if is_logged_failure(response.error):
mark_failure_logged(err)
raise err
Expand Down
6 changes: 4 additions & 2 deletions packages/genkit/src/genkit/_ai/_aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@
from genkit._core._reflection_v2 import ReflectionServerV2
from genkit._core._registry import Registry, define_dynamic_action_provider as define_dap_block
from genkit._core._telemetry._attrs import metadata_key
from genkit._core._telemetry._http import maybe_inject_dev_instrumentation
from genkit._core._telemetry._http import mark_already_sourced, maybe_inject_dev_instrumentation
from genkit._core._telemetry._instrumentation import run_in_new_span
from genkit._core._tool import Tool, ToolContext
from genkit._core._typing import (
Expand Down Expand Up @@ -2204,12 +2204,14 @@ async def generate_operation(
# This call is "give me the ticket." A start that already
# failed is not that ticket — while-not-done would poll it
# as a live job.
raise GenkitError(
err = GenkitError(
status=response.error.status or 'INTERNAL',
message=response.error.message,
details=response.error.details,
reason=response.error.reason,
)
mark_already_sourced(err)
raise err
if not response.operation:
raise missing_operation_error(name=model_action.name)
return as_model_operation(response.operation, name=model_action.name, status='INTERNAL')
13 changes: 10 additions & 3 deletions packages/genkit/src/genkit/_ai/_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -795,6 +795,13 @@ async def stop_model() -> None:
return StoppableStream(chunks=channel, stop=stop_model), task


def failed_span_message(response: ModelResponse) -> str | None:
"""Status text for a generate span whose response came back failed."""
if response._failure is not None:
return response._failure.trace_message or response._failure.message
return response.error.message if response.error is not None else None


def define_generate_action(ai: _aio.Genkit) -> None:
"""Register the generation action triggered by the Dev UI."""

Expand All @@ -810,7 +817,7 @@ async def generate_action_fn(
context=dict(ctx.context),
)
if response.error is not None:
set_span_state('error')
set_span_state('error', message=failed_span_message(response))
return response

_ = ai._registry.register_action(
Expand Down Expand Up @@ -853,7 +860,7 @@ async def body(_span: SpanContext) -> ModelResponse:
context=context,
)
if result.error is not None:
set_span_state('error')
set_span_state('error', message=failed_span_message(result))
return result

return await run_in_new_span('generate', body, action_type='util', input=options)
Expand Down Expand Up @@ -1882,7 +1889,7 @@ async def next_turn(_span: SpanContext) -> ModelResponse:
resolved=resolved,
)
if result.error is not None:
set_span_state('error')
set_span_state('error', message=failed_span_message(result))
return result

return await hop(
Expand Down
3 changes: 2 additions & 1 deletion packages/genkit/src/genkit/_ai/_prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
from genkit._ai import _aio
from genkit._ai._generate import (
CallScope,
failed_span_message,
generate_action,
register_middleware,
register_tools,
Expand Down Expand Up @@ -485,7 +486,7 @@ async def run() -> ModelResponse:
async def body(_span: SpanContext) -> ModelResponse:
result = await run()
if result.error is not None:
set_span_state('error')
set_span_state('error', message=failed_span_message(result))
return result

result = await run_in_new_span(
Expand Down
5 changes: 3 additions & 2 deletions packages/genkit/src/genkit/_core/_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -1655,8 +1655,9 @@ async def body(span: SpanContext) -> OutputT:
else:
output = await self._invoke(input, ctx)
except Interrupt as e:
if e.metadata:
span.set_metadata({'interrupt': e.metadata})
# the Dev UI shows the interrupted icon off this key, so a bare
# interrupt with nothing to say still needs it.
span.set_metadata({'interrupt': e.metadata or True})
# Only generate's tool loop turns an Interrupt into a pause.
# With no tool above, it is a BaseException that `except
# Exception` handlers (web adapters, agent transports) would
Expand Down
7 changes: 6 additions & 1 deletion packages/genkit/src/genkit/_core/_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,8 @@ class Interrupt(BaseException):
swallow it and skip the approval. Catch ``Interrupt`` by name if a tool
needs to clean up, then re-raise. Raised anywhere else (a flow, an
agent turn body), the action fails with ``GenkitError`` INTERNAL.
Tracing treats it as control flow, not a failed span.
In the trace the tool's own span shows as interrupted; the generate
that paused on it stays green.
"""

def __init__(self, metadata: dict[str, Any] | None = None) -> None:
Expand Down Expand Up @@ -886,6 +887,9 @@ class BoxedFailure:
is_public: bool = False
details: Any = None # noqa: ANN401
source: str | None = None
# A plain exception's own words, without the type name ``message`` adds.
# The caller gets ``internal error``; the failed generate span shows this.
trace_message: str = ''

@classmethod
def from_exc(cls, exc: BaseException) -> Self:
Expand All @@ -903,6 +907,7 @@ def from_exc(cls, exc: BaseException) -> Self:
return cls(
status='INTERNAL',
message=f'{type(exc).__name__}: {text}' if text else type(exc).__name__,
trace_message=text or type(exc).__name__,
)

def to_exception(self) -> GenkitError:
Expand Down
61 changes: 57 additions & 4 deletions packages/genkit/src/genkit/_core/_telemetry/_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from __future__ import annotations

import asyncio
import contextlib
import json
import os
import secrets
Expand Down Expand Up @@ -77,11 +78,20 @@ class ActiveSpan:
attributes: dict[str, object] = field(default_factory=dict)
status_code: int = 0
status_message: str | None = None
parent: ActiveSpan | None = field(default=None, repr=False, compare=False)
has_failed_child: bool = field(default=False, repr=False, compare=False)


_parent_span: ContextVar[ActiveSpan | None] = ContextVar('genkit_direct_http_parent', default=None)


def note_child_failed(span: ActiveSpan) -> None:
curr = span.parent
while curr is not None and not curr.has_failed_child:
curr.has_failed_child = True
curr = curr.parent


class DirectSpanContext:
"""Span handle that writes ``genkit:*`` attributes onto the live span."""

Expand All @@ -104,10 +114,16 @@ def set_metadata(self, metadata: Mapping[str, object]) -> None:
encoded = f'Error encoding metadata: {e}'
self._span.attributes[metadata_key(str(key))] = encoded

def set_state(self, state: Literal['success', 'error']) -> None:
def set_state(self, state: Literal['success', 'error'], *, message: str | None = None) -> None:
self._span.attributes[Attr.STATE] = state
if state == State.ERROR:
self._span.status_code = 2
if message:
self._span.attributes[Attr.ERROR] = message
self._span.status_message = message
if not self._span.has_failed_child:
self._span.attributes[Attr.IS_FAILURE_SOURCE] = True
note_child_failed(self._span)


def now_unix_nano() -> int:
Expand Down Expand Up @@ -260,7 +276,10 @@ async def run_in_new_span(
name=metadata.name,
start_time_unix_nano=now_unix_nano(),
attributes=start_attributes(metadata, qualified_path=qualified_path, is_action=is_action),
parent=parent,
)
if parent is None:
span.attributes[Attr.IS_ROOT] = True
self.sink.export_spans([span], resource_attributes=self.resource_attributes)
path_token = parent_path_context.set(qualified_path)
parent_token = _parent_span.set(span)
Expand All @@ -274,9 +293,12 @@ async def run_in_new_span(
span.attributes[Attr.STATE] = State.SUCCESS
span.status_code = 1
return result
except Interrupt:
span.attributes[Attr.STATE] = State.SUCCESS
span.status_code = 1
except Interrupt as e:
# the Dev UI draws an interrupted tool from the error state plus
# genkit:metadata:interrupt; generate above it still succeeds.
span.attributes[Attr.STATE] = State.ERROR
span.status_code = 2
mark_failure_source(span=span, exc=e)
raise
except (asyncio.CancelledError, KeyboardInterrupt):
raise
Expand All @@ -287,6 +309,8 @@ async def run_in_new_span(
span.attributes[Attr.ERROR] = err_text
span.status_code = 2
span.status_message = str(actual)
note_child_failed(span)
mark_failure_source(span=span, exc=actual)
raise
finally:
span.end_time_unix_nano = now_unix_nano()
Expand All @@ -310,6 +334,35 @@ class DevUIInstrumentation(DirectHttpInstrumentation):
"""


# Set on an exception once the span it was raised in claims it. Every span it
# then passes through still turns red, but only the first one says the failure
# started there, so the Traces tab can point at the culprit.
# Only explicit causes (`raise ... from e`, `GenkitError(cause=e)`) count as
# derived, same as JS `cause` and Go `%w`. Implicit `__context__` does not.
FAILURE_SOURCE_MARK = '_genkit_failure_source'


def mark_failure_source(*, span: ActiveSpan, exc: BaseException) -> None:
seen: set[int] = set()
current: BaseException | None = exc
while current is not None and id(current) not in seen:
if getattr(current, FAILURE_SOURCE_MARK, False):
return
seen.add(id(current))
current = current.__cause__
span.attributes[Attr.IS_FAILURE_SOURCE] = True
with contextlib.suppress(AttributeError, TypeError):
setattr(exc, FAILURE_SOURCE_MARK, True)


def mark_already_sourced(exc: BaseException) -> None:
"""Stamp an error rebuilt from a boxed response whose span already claimed the failure."""
if not is_instrumented_by(DirectHttpInstrumentation):
return
with contextlib.suppress(AttributeError, TypeError):
setattr(exc, FAILURE_SOURCE_MARK, True)


def reset_parent_span() -> None:
_parent_span.set(None)

Expand Down
14 changes: 7 additions & 7 deletions packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def set_metadata(self, metadata: Mapping[str, object]) -> None:
"""Attach custom metadata. Safe to call multiple times."""
...

def set_state(self, state: SpanState) -> None:
def set_state(self, state: SpanState, *, message: str | None = None) -> None:
"""Override genkit:state. ``error`` marks a failed generate that returned."""
...

Expand Down Expand Up @@ -255,11 +255,11 @@ def set_custom_metadata_attributes(attributes: Mapping[str, object]) -> None:
span.set_metadata(attributes)


def set_span_state(state: SpanState) -> None:
"""Write genkit:state on the active span. No-op outside a span."""
def set_span_state(state: SpanState, *, message: str | None = None) -> None:
"""Write genkit:state (and an error's status text) on the active span. No-op outside a span."""
span = current_span.get()
if span is not None:
span.set_state(state)
span.set_state(state, message=message)


async def run_in_new_span(
Expand Down Expand Up @@ -336,7 +336,7 @@ def span_id(self) -> str:
def set_metadata(self, metadata: Mapping[str, object]) -> None:
return

def set_state(self, state: SpanState) -> None:
def set_state(self, state: SpanState, *, message: str | None = None) -> None:
return


Expand All @@ -359,10 +359,10 @@ def set_metadata(self, metadata: Mapping[str, object]) -> None:
with contextlib.suppress(Exception):
span.set_metadata(metadata)

def set_state(self, state: SpanState) -> None:
def set_state(self, state: SpanState, *, message: str | None = None) -> None:
for span in self._spans:
with contextlib.suppress(Exception):
span.set_state(state)
span.set_state(state, message=message)

def _first_non_empty(self, get: Callable[[SpanContext], str]) -> str:
for span in self._spans:
Expand Down
Loading
Loading