From f474b5e3772f4850315ab801d858f055e32e9447 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Fri, 6 Nov 2026 12:12:03 -0600 Subject: [PATCH 1/8] fix(py/agents): redact custom agent exception text in failed turns --- .../genkit/src/genkit/_ai/_agents/_base.py | 2 +- .../genkit/src/genkit/_ai/_agents/_runtime.py | 46 +++++++- packages/genkit/src/genkit/_ai/_generate.py | 14 ++- .../tests/genkit/ai/agent_chat_client_test.py | 109 ++++++++++++++++-- .../tests/genkit/ai/agent_conformance_test.py | 7 +- .../tests/genkit/ai/agent_detach_test.py | 4 +- .../tests/genkit/ai/exp_agents_import_test.py | 8 +- 7 files changed, 169 insertions(+), 21 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_agents/_base.py b/packages/genkit/src/genkit/_ai/_agents/_base.py index c4d7654c8..2758423f7 100644 --- a/packages/genkit/src/genkit/_ai/_agents/_base.py +++ b/packages/genkit/src/genkit/_ai/_agents/_base.py @@ -261,7 +261,7 @@ async def bidi_fn( except GenkitError as e: return AgentOutput( finish_reason=AgentFinishReason.FAILED, - error=to_error_details(e), + error=to_error_details(e, agent=name), state=(init.state if store is None and init.state is not None else None), ) diff --git a/packages/genkit/src/genkit/_ai/_agents/_runtime.py b/packages/genkit/src/genkit/_ai/_agents/_runtime.py index 485475074..0a5558358 100644 --- a/packages/genkit/src/genkit/_ai/_agents/_runtime.py +++ b/packages/genkit/src/genkit/_ai/_agents/_runtime.py @@ -40,7 +40,13 @@ from genkit._ai._agents._session_stores._util import session_id_of from genkit._ai._agents._snapshot import walk_back_to_resumable from genkit._ai._agents._types import ChunkTransform, StateTransform, TurnContext, TurnResult -from genkit._ai._generate import CallScope, generate_action +from genkit._ai._generate import ( + INTERNAL_FINISH_MESSAGE, + CallScope, + boxed_finish_message, + generate_action, + log_dropped_failure, +) from genkit._ai._json_patch import diff_json from genkit._core._action import ActionRunContext, get_current_context from genkit._core._channel import CloseableQueue, QueueShutDown @@ -53,6 +59,7 @@ PublicError, StatusName, TaskGroupError, + attached_cause, interrupt_escape_error, ) from genkit._core._logger import get_logger @@ -105,8 +112,10 @@ def __init__( get_parent_snapshot_id: Callable[[], str | None] | None = None, on_begin_turn: Callable[[], Awaitable[None]] | None = None, on_end_turn: Callable[[AgentFinishReason | None], Awaitable[str | None]] | None = None, + agent_name: str | None = None, ) -> None: self.session = session + self.agent_name = agent_name self.turn_inputs = turn_inputs self.store = store self.get_parent_snapshot_id = get_parent_snapshot_id @@ -220,7 +229,7 @@ async def body(span: SpanContext, turn_input: AgentInput = inp, ctx: TurnContext else: raise self.last_turn_finish_reason = AgentFinishReason.FAILED - self.last_turn_error = to_error_details(turn_error) + self.last_turn_error = to_error_details(turn_error, agent=self.agent_name) if self.on_end_turn is not None: await self.on_end_turn(AgentFinishReason.FAILED) @@ -523,6 +532,7 @@ def __init__( get_parent_snapshot_id=lambda: self.last_snapshot.snapshot_id if self.last_snapshot else None, on_begin_turn=self.reset_custom_patch_turn, on_end_turn=self.emit_turn_end, + agent_name=name, ) session.on_custom_changed(self.emit_custom_patch) @@ -846,7 +856,7 @@ def finalize(existing: SessionSnapshot | None) -> SessionSnapshot | None: parent_id=pending_snap.parent_id or '', status=SnapshotStatus.FAILED if is_failed else SnapshotStatus.COMPLETED, state=state, - error=(to_error_details(fn_err) if fn_err else turn_err), + error=(to_error_details(fn_err, agent=self.name) if fn_err else turn_err), finish_reason=finish_reason, created_at=existing.created_at if existing else now, ) @@ -1167,7 +1177,7 @@ def on_chunk(chunk: ModelResponseChunk) -> None: # --------------------------------------------------------------------------- -def to_error_details(exc: BaseException) -> Failure: +def to_error_details(exc: BaseException, *, agent: str | None = None) -> Failure: """A turn failure as data, with the status classified like Go's ``status.Classified``. Classifies the top-level exception; Go also walks the wrapped chain @@ -1176,12 +1186,30 @@ def to_error_details(exc: BaseException) -> Failure: Only a GenkitError names its own status. A third-party ``.status`` attribute (aiohttp's ``status=429``) isn't a Genkit status, so it never leaks through. + + The message follows generate's rule for a raising tool: a GenkitError + keeps its own text (an INTERNAL one wrapping a foreign cause does not), + and anything else becomes ``internal error``. The Failure lands on + ``AgentOutput.error`` and in snapshots, which a served agent returns + in a 200, so raw exception text would reach the client. What gets + hidden is logged here with its traceback instead. + + Args: + exc: The exception that ended the turn or invocation. + agent: Agent name for the server-side log line, when known. """ status: StatusName details: dict[str, Any] | None = None if isinstance(exc, GenkitError): status = exc.status - message = exc.message + cause = attached_cause(exc) + if cause is not None and interrupt_escape_error(cause) is not None: + # interrupt_escape_error's own sentence; the attached Interrupt + # is tool metadata, not foreign exception text. + message = exc.message + else: + message = boxed_finish_message(exc=exc, pipe_failed=False) + redacted = message != exc.message if isinstance(exc.details, Mapping) and exc.details: details = dict(cast(Mapping[str, Any], exc.details)) else: @@ -1192,7 +1220,13 @@ def to_error_details(exc: BaseException) -> Failure: status = 'DEADLINE_EXCEEDED' else: status = 'INTERNAL' - message = str(exc) or 'Internal failure' + message = INTERNAL_FINISH_MESSAGE + redacted = True + # A prompt agent re-raises generate's already-boxed error as a fresh + # GenkitError carrying ``internal error``; nothing is hidden there, and + # generate logged the cause, so only log when this call hid text. + if redacted: + log_dropped_failure(exc, agent=agent) return Failure(status=status, message=message, details=details) diff --git a/packages/genkit/src/genkit/_ai/_generate.py b/packages/genkit/src/genkit/_ai/_generate.py index 6b7b9d867..4400d302f 100644 --- a/packages/genkit/src/genkit/_ai/_generate.py +++ b/packages/genkit/src/genkit/_ai/_generate.py @@ -1373,7 +1373,13 @@ def boxed_finish_message(*, exc: BaseException, pipe_failed: bool) -> str: _LOGGED_ATTR = '_genkit_failure_logged' -def log_dropped_failure(exc: BaseException, *, model: str | None = None, tool: str | None = None) -> None: +def log_dropped_failure( + exc: BaseException, + *, + model: str | None = None, + tool: str | None = None, + agent: str | None = None, +) -> None: """Log a failure whose cause boxing hides behind ``internal error``. The caller only gets ``finish_reason=failed`` with ``internal error``, so @@ -1385,6 +1391,8 @@ def log_dropped_failure(exc: BaseException, *, model: str | None = None, tool: s exc: The exception about to be boxed. model: Model the turn was calling, when known. tool: Tool that raised, when known. Named over ``model``. + agent: Agent whose turn raised, when known. ``tool`` and ``model`` + are named over it. """ if getattr(exc, _LOGGED_ATTR, False): return @@ -1397,6 +1405,8 @@ def log_dropped_failure(exc: BaseException, *, model: str | None = None, tool: s fields['model'] = model if tool: fields['tool'] = tool + if agent: + fields['agent'] = agent span = current_span.get() if span is not None and span.trace_id: fields['trace_id'] = span.trace_id @@ -1404,6 +1414,8 @@ def log_dropped_failure(exc: BaseException, *, model: str | None = None, tool: s culprit = f'tool {tool!r}' elif model: culprit = f'model {model!r}' + elif agent: + culprit = f'agent {agent!r}' else: culprit = 'generate' logger.error('%s raised, returning finish_reason=failed', culprit, exc_info=exc, **fields) diff --git a/packages/genkit/tests/genkit/ai/agent_chat_client_test.py b/packages/genkit/tests/genkit/ai/agent_chat_client_test.py index 20ff44bb8..19324178e 100644 --- a/packages/genkit/tests/genkit/ai/agent_chat_client_test.py +++ b/packages/genkit/tests/genkit/ai/agent_chat_client_test.py @@ -15,12 +15,14 @@ from __future__ import annotations import asyncio -from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Callable +from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Callable, Mapping, Sequence from typing import Any import anyio import pytest +import structlog from pydantic import BaseModel +from structlog.testing import capture_logs from genkit import Part from genkit._ai._agents._base import Agent, define_custom_agent @@ -36,7 +38,7 @@ from genkit._ai._agents._types import StateManagement, TurnResult from genkit._ai._json_patch import apply_json_patch from genkit._core._channel import CloseableQueue -from genkit._core._error import ErrorReason, Failure, GenkitError, Interrupt +from genkit._core._error import ErrorReason, Failure, GenkitError, Interrupt, PublicError from genkit._core._model import ( AgentInit, AgentInput, @@ -1738,6 +1740,85 @@ async def test_send_on_failed_turn_with_reason_reads_reason() -> None: assert err.reason is ErrorReason.TOOL_FAILED +def _logged_errors(entries: Sequence[Mapping[str, Any]]) -> list[Mapping[str, Any]]: + return [e for e in entries if e['log_level'] == 'error'] + + +@pytest.mark.asyncio +async def test_custom_agent_raising_foreign_error_redacts_message_and_logs_cause() -> None: + """A ValueError's text stays server-side; the caller gets INTERNAL 'internal error'.""" + structlog.reset_defaults() + agent = _flaky( + Genkit(), + 'ordersDb', + store=InMemorySessionStore(), + fail=ValueError('db password=hunter2'), + ) + + with capture_logs() as entries: + res = await agent.chat().send('please fail now') + + err = _assert_failed(res, message='internal error') + assert err.status == 'INTERNAL' + assert 'hunter2' not in err.model_dump_json() + errors = _logged_errors(entries) + assert len(errors) == 1 + assert errors[0]['event'] == "agent 'ordersDb' raised, returning finish_reason=failed" + assert errors[0]['agent'] == 'ordersDb' + assert str(errors[0]['exc_info']) == 'db password=hunter2' + + +@pytest.mark.asyncio +async def test_custom_agent_raising_genkit_error_keeps_status_and_message() -> None: + """A GenkitError is the author's chosen caller-facing failure, so it passes through unlogged.""" + structlog.reset_defaults() + agent = _flaky( + Genkit(), + 'orderLookup', + store=InMemorySessionStore(), + fail=GenkitError(status='NOT_FOUND', message='no order A-17'), + ) + + with capture_logs() as entries: + res = await agent.chat().send('please fail now') + + err = _assert_failed(res, message='no order A-17') + assert err.status == 'NOT_FOUND' + assert _logged_errors(entries) == [] + + +@pytest.mark.asyncio +async def test_prompt_agent_with_crashing_tool_logs_cause_once() -> None: + """generate already boxed and logged the tool error; the agent runtime does not log it again.""" + structlog.reset_defaults() + ai = Genkit() + pm, _ = define_scripted_model(ai) + + @ai.tool(name='check_allergens') + async def check_allergens(_: dict) -> str: # noqa: ARG001 + raise RuntimeError('allergen db password=hunter2') + + pm.responses = [ + ModelResponse( + message=Message( + role=Role.MODEL, + content=[Part(tool_request=ToolRequest(name='check_allergens', input={}, ref='1'))], + ), + finish_reason=FinishReason.STOP, + ) + ] + agent = ai.define_agent(name='allergyAgent', model='scriptedModel', tools=['check_allergens']) + + with capture_logs() as entries: + res = await agent.chat().send('is the tartine nut-free?') + + err = _assert_failed(res, message='internal error') + assert err.status == 'INTERNAL' + errors = _logged_errors(entries) + assert len(errors) == 1 + assert errors[0]['tool'] == 'check_allergens' + + @pytest.mark.asyncio async def test_send_on_failed_turn_keeps_last_good_snapshot_id() -> None: """res.snapshot_id and chat.snapshot_id both stay on the last completed snapshot.""" @@ -2306,17 +2387,29 @@ def __init__(self) -> None: {'reason': 'TOOL_NOT_FOUND'}, ), (GenkitError(status='ABORTED', message='stopped'), 'ABORTED', 'stopped', None), - (asyncio.CancelledError(), 'CANCELLED', 'Internal failure', None), - (TimeoutError('kitchen printer timed out'), 'DEADLINE_EXCEEDED', 'kitchen printer timed out', None), - (asyncio.TimeoutError('kitchen printer timed out'), 'DEADLINE_EXCEEDED', 'kitchen printer timed out', None), - (_ClientResponseError(), 'INTERNAL', '429, message=Too Many Requests', None), - (ValueError('bad table number'), 'INTERNAL', 'bad table number', None), + (PublicError('PERMISSION_DENIED', 'table 12 is reserved'), 'PERMISSION_DENIED', 'table 12 is reserved', None), + # An INTERNAL wrapper around a foreign cause hides it, as generate does for a tool. + ( + GenkitError(status='INTERNAL', message='pos sync failed', cause=ValueError('dsn=pg://admin@10.0.0.4')), + 'INTERNAL', + 'internal error', + None, + ), + (asyncio.CancelledError(), 'CANCELLED', 'internal error', None), + (TimeoutError('kitchen printer 10.0.0.9 timed out'), 'DEADLINE_EXCEEDED', 'internal error', None), + (asyncio.TimeoutError('kitchen printer 10.0.0.9 timed out'), 'DEADLINE_EXCEEDED', 'internal error', None), + (_ClientResponseError(), 'INTERNAL', 'internal error', None), + (ValueError('db password=hunter2'), 'INTERNAL', 'internal error', None), ], ) def test_to_error_details_classifies_status_like_go( exc: BaseException, status: str, message: str, details: dict[str, Any] | None ) -> None: - """Only a GenkitError names its status; a foreign int ``.status`` (aiohttp's 429) is INTERNAL.""" + """Only a GenkitError names its status and message; anything else is classified and redacted. + + A foreign int ``.status`` (aiohttp's 429) is INTERNAL, and no foreign + exception text reaches the Failure. + """ failure = to_error_details(exc) assert failure.status == status diff --git a/packages/genkit/tests/genkit/ai/agent_conformance_test.py b/packages/genkit/tests/genkit/ai/agent_conformance_test.py index bab8e813b..5225bacfc 100644 --- a/packages/genkit/tests/genkit/ai/agent_conformance_test.py +++ b/packages/genkit/tests/genkit/ai/agent_conformance_test.py @@ -555,10 +555,13 @@ def _register_custom_agents(*, ai: Genkit, agents: dict[str, Agent]) -> None: ) # Raise inside the turn so run() records last_turn_error, then return - # result() so an attached caller gets a graceful failed output. + # result() so an attached caller gets a graceful failed output. A + # GenkitError, not a bare exception: the spec reads the message back off + # the snapshot, and Python records foreign exception text as 'internal + # error' (the cause goes to the server log). async def failing_agent_fn(session_runner: SessionRunner, _ctx: AgentContext) -> AgentResult: async def handle_turn(_inp: AgentInput, _tc: TurnContext) -> TurnResult | None: - raise RuntimeError('intentional failure') + raise GenkitError(status='INTERNAL', message='intentional failure') await session_runner.run(handle_turn) return await session_runner.result() diff --git a/packages/genkit/tests/genkit/ai/agent_detach_test.py b/packages/genkit/tests/genkit/ai/agent_detach_test.py index 4cc4404ee..08f255db6 100644 --- a/packages/genkit/tests/genkit/ai/agent_detach_test.py +++ b/packages/genkit/tests/genkit/ai/agent_detach_test.py @@ -474,7 +474,9 @@ async def handle_turn(_inp: AgentInput, _: TurnContext) -> None: assert snap.status == SnapshotStatus.FAILED assert snap.finish_reason == AgentFinishReason.FAILED assert snap.error is not None - assert 'intentional failure' in (snap.error.message or '') + # The RuntimeError's text stays server-side; the snapshot is client-readable. + assert snap.error.status == 'INTERNAL' + assert snap.error.message == 'internal error' @pytest.mark.asyncio diff --git a/packages/genkit/tests/genkit/ai/exp_agents_import_test.py b/packages/genkit/tests/genkit/ai/exp_agents_import_test.py index 08ae5e1fb..b062bfd1c 100644 --- a/packages/genkit/tests/genkit/ai/exp_agents_import_test.py +++ b/packages/genkit/tests/genkit/ai/exp_agents_import_test.py @@ -168,7 +168,11 @@ async def test_exp_genkit_still_generates() -> None: @pytest.mark.asyncio async def test_agent_turn_awaiting_failing_flow_reports_message_without_details() -> None: - """A turn that awaits a flow raising RuntimeError('db rejected') records that message and no details.""" + """A turn that awaits a flow raising RuntimeError('db rejected') records 'internal error' and no details. + + The flow wraps the RuntimeError as an INTERNAL GenkitError with a foreign + cause, so its text stays server-side, as generate does for a raising tool. + """ ai = Genkit() @ai.flow() @@ -189,6 +193,6 @@ async def handle_turn(inp: AgentInput, __: TurnContext) -> TurnResult | None: assert res.finish_reason == AgentFinishReason.FAILED assert res.error is not None - assert res.error.message == 'db rejected' + assert res.error.message == 'internal error' assert res.error.details is None assert res.error.status == 'INTERNAL' From b0af7e0d9695788b230f3e34076d1f2b57f87328 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Tue, 10 Nov 2026 00:52:09 -0600 Subject: [PATCH 2/8] refactor(py/agents): keep SessionRunner's agent name private SessionRunner is exported from genkit.exp.agent, so a public agent_name attribute shows up on every custom agent's runner. It only feeds the redaction log line. --- packages/genkit/src/genkit/_ai/_agents/_runtime.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_agents/_runtime.py b/packages/genkit/src/genkit/_ai/_agents/_runtime.py index 0a5558358..db804069f 100644 --- a/packages/genkit/src/genkit/_ai/_agents/_runtime.py +++ b/packages/genkit/src/genkit/_ai/_agents/_runtime.py @@ -115,7 +115,8 @@ def __init__( agent_name: str | None = None, ) -> None: self.session = session - self.agent_name = agent_name + # Names the agent in the server-side log when a turn error is redacted. + self._agent_name = agent_name self.turn_inputs = turn_inputs self.store = store self.get_parent_snapshot_id = get_parent_snapshot_id @@ -229,7 +230,7 @@ async def body(span: SpanContext, turn_input: AgentInput = inp, ctx: TurnContext else: raise self.last_turn_finish_reason = AgentFinishReason.FAILED - self.last_turn_error = to_error_details(turn_error, agent=self.agent_name) + self.last_turn_error = to_error_details(turn_error, agent=self._agent_name) if self.on_end_turn is not None: await self.on_end_turn(AgentFinishReason.FAILED) From a2e672d053c9db27232a8bbdd82d12a6ce5656e0 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Tue, 10 Nov 2026 01:25:18 -0600 Subject: [PATCH 3/8] fix(py/agents): redact agent failures on the wire, not when recorded Recording 'internal error' in to_error_details lost the text for in-process callers, the store, and the Dev UI, and still let any non-public GenkitError (NOT_FOUND, provider_error 429) reach HTTP callers verbatim. Move redaction to genkit.web, where every adapter frames results: result_json and to_sse pass a failed AgentOutput/SessionSnapshot error through client_safe_failure. A PublicError's Failure is marked (private, unserialized flag, like Go's status.Error.Public) and goes out as is; anything else keeps its status with a generic message and no details. Same rule as error_body for flows and Go's clientSafeError. to_error_details keeps the exception text again, matching JS and Go, so customAgentFailing goes back to a plain RuntimeError and the shared agent.yaml case runs on real behavior. The server-side log with traceback stays for causes generate's rule would hide. --- .../tests/agent_handler_test.py | 96 ++++++++++++++++++- .../genkit/src/genkit/_ai/_agents/_runtime.py | 43 +++++---- packages/genkit/src/genkit/_core/_error.py | 29 +++++- packages/genkit/src/genkit/web/__init__.py | 7 +- packages/genkit/src/genkit/web/_sse.py | 25 ++++- .../tests/genkit/ai/agent_chat_client_test.py | 40 +++++--- .../tests/genkit/ai/agent_conformance_test.py | 7 +- .../tests/genkit/ai/agent_detach_test.py | 4 +- .../tests/genkit/ai/exp_agents_import_test.py | 8 +- packages/genkit/tests/genkit/core/web_test.py | 21 ++++ 10 files changed, 222 insertions(+), 58 deletions(-) diff --git a/packages/genkit-fastapi/tests/agent_handler_test.py b/packages/genkit-fastapi/tests/agent_handler_test.py index 7fa26d91f..c425d299a 100644 --- a/packages/genkit-fastapi/tests/agent_handler_test.py +++ b/packages/genkit-fastapi/tests/agent_handler_test.py @@ -5,6 +5,7 @@ from __future__ import annotations +import asyncio import json import logging import re @@ -20,17 +21,30 @@ from genkit import ( ErrorReason, FinishReason, + GenkitError, Message, ModelResponse, ModelResponseChunk, Part, + PublicError, Role, ) # error_from_http is private: this test pins the client-side HTTP error mapping. from genkit._ai._agents._client import error_from_http # noqa: TID251 from genkit.exp import Genkit -from genkit.exp.agent import AgentInit, InMemorySessionStore +from genkit.exp.agent import ( + AgentContext, + AgentInit, + AgentInput, + AgentResult, + InMemorySessionStore, + SessionRunner, + SnapshotStatus, + TurnContext, + TurnResult, +) +from genkit.plugin_api import provider_error from genkit.testing import define_scripted_model from genkit.web import to_sse @@ -340,3 +354,83 @@ async def to_sse_route() -> StreamingResponse: assert frames(served.text) == expected assert frames(hand.post('/request?stream=true', json=wire_body).text) == expected assert frames(hand.post('/to_sse').text) == expected + + +class _ProviderHttpError(Exception): + """Stands in for an SDK's HTTP error whose text carries the request URL.""" + + +def _failing_agent(name: str, exc: Exception) -> Any: + """A server-managed custom agent whose every turn raises ``exc``.""" + ai = Genkit() + + async def fn(session_runner: SessionRunner, _ctx: AgentContext) -> AgentResult: + async def turn(_inp: AgentInput, _tc: TurnContext) -> TurnResult | None: + raise exc + + await session_runner.run(turn) + return await session_runner.result() + + return ai.define_custom_agent(name=name, fn=fn, store=InMemorySessionStore()) + + +@pytest.mark.parametrize( + ('exc', 'expected'), + [ + (ValueError('db password=hunter2'), {'status': 'INTERNAL', 'message': 'Internal Error'}), + ( + PublicError('PERMISSION_DENIED', 'table 12 is reserved'), + {'status': 'PERMISSION_DENIED', 'message': 'table 12 is reserved'}, + ), + ( + GenkitError(status='NOT_FOUND', message='no row in tenant_secrets for key=hunter2'), + {'status': 'NOT_FOUND', 'message': 'Not Found'}, + ), + ( + provider_error(_ProviderHttpError('429 https://api.example.com/v1?key=hunter2'), http_status=429), + {'status': 'RESOURCE_EXHAUSTED', 'message': 'Resource Exhausted'}, + ), + ], + ids=['foreign', 'public', 'genkit_not_found', 'provider_429'], +) +@pytest.mark.parametrize('stream', [False, True], ids=['json', 'sse']) +def test_failed_turn_sends_only_public_error_text(exc: Exception, expected: dict[str, str], stream: bool) -> None: + """A failed turn is a 200; its error follows error_body's rule, so only a PublicError's text goes out.""" + response = client(_failing_agent('ordersDb', exc)).post( + f'/api/chat?stream={str(stream).lower()}', json={'message': 'refund A-17'} + ) + + assert response.status_code == 200 + result = sse_events(response.text)[-1]['result'] if stream else response.json()['result'] + assert result['finishReason'] == 'failed' + assert result['error'] == expected + assert 'hunter2' not in response.text + + +@pytest.mark.asyncio +async def test_failed_turn_keeps_error_text_in_process_and_in_the_store() -> None: + """Redaction is at the wire: res.error and the stored snapshot keep the exception's text.""" + agent = _failing_agent('ordersDb', RuntimeError('pos sync failed: dsn=pg://admin@10.0.0.4')) + + # 1. Detach so the background finalize writes the failure into the store. + out = await agent.run( + input=AgentInput(message=Message(role=Role.USER, content=[Part.from_text('refund A-17')]), detach=True), + init=AgentInit(), + ) + snapshot_id = out.response.snapshot_id + assert snapshot_id is not None + for _ in range(200): + snap = await agent.get_snapshot_data(snapshot_id=snapshot_id) + if snap is not None and snap.status == SnapshotStatus.FAILED: + break + await asyncio.sleep(0.01) + else: + raise AssertionError('detached turn never finalized') + + # 2. In process, the stored snapshot keeps the exception's text. + assert snap.error is not None + assert snap.error.message == 'pos sync failed: dsn=pg://admin@10.0.0.4' + + # 3. Over HTTP, getSnapshot sends the generic message. + served = client(agent).post('/api/chat/getSnapshot', json={'snapshotId': snapshot_id}) + assert served.json()['result']['error'] == {'status': 'INTERNAL', 'message': 'Internal Error'} diff --git a/packages/genkit/src/genkit/_ai/_agents/_runtime.py b/packages/genkit/src/genkit/_ai/_agents/_runtime.py index db804069f..7dedee42c 100644 --- a/packages/genkit/src/genkit/_ai/_agents/_runtime.py +++ b/packages/genkit/src/genkit/_ai/_agents/_runtime.py @@ -41,7 +41,6 @@ from genkit._ai._agents._snapshot import walk_back_to_resumable from genkit._ai._agents._types import ChunkTransform, StateTransform, TurnContext, TurnResult from genkit._ai._generate import ( - INTERNAL_FINISH_MESSAGE, CallScope, boxed_finish_message, generate_action, @@ -61,6 +60,7 @@ TaskGroupError, attached_cause, interrupt_escape_error, + mark_public_failure, ) from genkit._core._logger import get_logger from genkit._core._model import ( @@ -1188,12 +1188,13 @@ def to_error_details(exc: BaseException, *, agent: str | None = None) -> Failure attribute (aiohttp's ``status=429``) isn't a Genkit status, so it never leaks through. - The message follows generate's rule for a raising tool: a GenkitError - keeps its own text (an INTERNAL one wrapping a foreign cause does not), - and anything else becomes ``internal error``. The Failure lands on - ``AgentOutput.error`` and in snapshots, which a served agent returns - in a 200, so raw exception text would reach the client. What gets - hidden is logged here with its traceback instead. + The Failure keeps the exception's own text, like JS ``toErrorDetails`` + and Go ``convertKeepText``, so in-process callers, the session store and + the Dev UI see what went wrong. A served agent's HTTP caller doesn't: + ``genkit.web`` swaps in a generic message unless the turn raised a + ``PublicError`` (see ``client_safe_failure``). A cause that generate's + rule for a raising tool would hide is also logged here with its + traceback, so the server log has it when the wire doesn't. Args: exc: The exception that ended the turn or invocation. @@ -1203,14 +1204,14 @@ def to_error_details(exc: BaseException, *, agent: str | None = None) -> Failure details: dict[str, Any] | None = None if isinstance(exc, GenkitError): status = exc.status + message = exc.message cause = attached_cause(exc) - if cause is not None and interrupt_escape_error(cause) is not None: - # interrupt_escape_error's own sentence; the attached Interrupt - # is tool metadata, not foreign exception text. - message = exc.message - else: - message = boxed_finish_message(exc=exc, pipe_failed=False) - redacted = message != exc.message + # interrupt_escape_error's sentence isn't foreign text: the attached + # Interrupt is tool metadata. A prompt agent re-raises generate's + # already-boxed failure as a fresh GenkitError carrying + # ``internal error``; generate logged that cause already. + escaped_interrupt = cause is not None and interrupt_escape_error(cause) is not None + hides_cause = not escaped_interrupt and boxed_finish_message(exc=exc, pipe_failed=False) != exc.message if isinstance(exc.details, Mapping) and exc.details: details = dict(cast(Mapping[str, Any], exc.details)) else: @@ -1221,14 +1222,14 @@ def to_error_details(exc: BaseException, *, agent: str | None = None) -> Failure status = 'DEADLINE_EXCEEDED' else: status = 'INTERNAL' - message = INTERNAL_FINISH_MESSAGE - redacted = True - # A prompt agent re-raises generate's already-boxed error as a fresh - # GenkitError carrying ``internal error``; nothing is hidden there, and - # generate logged the cause, so only log when this call hid text. - if redacted: + message = str(exc) or 'Internal failure' + hides_cause = True + if hides_cause: log_dropped_failure(exc, agent=agent) - return Failure(status=status, message=message, details=details) + failure = Failure(status=status, message=message, details=details) + if isinstance(exc, PublicError): + mark_public_failure(failure) + return failure def to_agent_finish_reason(fr: FinishReason) -> AgentFinishReason: diff --git a/packages/genkit/src/genkit/_core/_error.py b/packages/genkit/src/genkit/_core/_error.py index f46fdf483..e36b37360 100644 --- a/packages/genkit/src/genkit/_core/_error.py +++ b/packages/genkit/src/genkit/_core/_error.py @@ -28,7 +28,7 @@ from enum import IntEnum from typing import Any, ClassVar, Literal, cast, get_args -from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError, model_validator +from pydantic import BaseModel, ConfigDict, PrivateAttr, TypeAdapter, ValidationError, model_validator from pydantic.alias_generators import to_camel from pydantic_core import ErrorDetails from pydantic_core.core_schema import ErrorType @@ -149,6 +149,10 @@ class Failure(_RuntimeErrorWire): status: StatusName | None = None # pyright: ignore[reportIncompatibleVariableOverride] # pyrefly: ignore[bad-override] details: dict[str, Any] | None = None # pyright: ignore[reportIncompatibleVariableOverride] # pyrefly: ignore[bad-override] + # Set when the failure came from a PublicError, so a served agent may send + # its message. Not serialized, like Go's status.Error.Public: a failure + # read back from a store or another process is redacted on the wire. + _public: bool = PrivateAttr(default=False) @model_validator(mode='before') @classmethod @@ -177,6 +181,29 @@ def reason(self) -> ErrorReason | None: return error_reason(self.details) +def mark_public_failure(failure: Failure) -> Failure: + """Mark ``failure`` as built from a PublicError, so a served agent sends its text.""" + failure._public = True + return failure + + +def client_safe_failure(failure: Failure) -> Failure: + """``failure`` as the HTTP caller of a served agent may see it. + + Same rule as ``error_body`` for a served flow: a PublicError's message + and details go out as is. Anything else keeps its status, since callers + branch on it, but gets a generic message for that status and no + details, so exception text, provider responses and internal ids stay in + the process, the store and the server log. Mirrors Go's + ``clientSafeError``. + """ + if failure._public: + return failure + status = failure.status + message = 'Internal Error' if status is None or status == 'INTERNAL' else status.replace('_', ' ').title() + return Failure(status=status, message=message) + + # Mapping of status names to HTTP status codes _STATUS_CODE_MAP: dict[StatusName, int] = { 'OK': 200, diff --git a/packages/genkit/src/genkit/web/__init__.py b/packages/genkit/src/genkit/web/__init__.py index 3992040d5..3fb01339b 100644 --- a/packages/genkit/src/genkit/web/__init__.py +++ b/packages/genkit/src/genkit/web/__init__.py @@ -25,8 +25,11 @@ HTTP status, or yield ``error_sse`` if a stream fails before ``to_sse`` starts. A PublicError's text reaches the caller, and bad input names the failing fields; anything else is a generic ``Internal Error`` so server details stay in -your logs. A ``ContextProvider`` reads the ``RequestData`` for one request and -returns what goes into the flow's context. +your logs. ``result_json`` and ``to_sse`` apply the same rule to a failed +agent turn's ``error`` (an ``AgentOutput`` or ``SessionSnapshot``), which goes +out in a 200: it keeps its status, and a non-public message becomes generic. +A ``ContextProvider`` reads the ``RequestData`` for one request and returns +what goes into the flow's context. ``to_sse`` frames a streaming handle (``flow.stream()``, ``ai.generate_stream()``, ``prompt.stream()``, ``chat.send_stream()``) as the diff --git a/packages/genkit/src/genkit/web/_sse.py b/packages/genkit/src/genkit/web/_sse.py index 2c33024f1..ae55665e8 100644 --- a/packages/genkit/src/genkit/web/_sse.py +++ b/packages/genkit/src/genkit/web/_sse.py @@ -25,8 +25,16 @@ from genkit._ai._agents._client import AgentChunk, AgentResponse from genkit._ai._prompt import ModelStreamResponse -from genkit._core._error import GenkitError, Interrupt, TaskGroupError, error_body, error_status, interrupt_escape_error -from genkit._core._model import ModelResponse +from genkit._core._error import ( + GenkitError, + Interrupt, + TaskGroupError, + client_safe_failure, + error_body, + error_status, + interrupt_escape_error, +) +from genkit._core._model import AgentOutput, ModelResponse, SessionSnapshot from genkit._core._typing import FinishReason # Compact JSON, the same bytes the FastAPI, Flask and Django adapters send. @@ -60,6 +68,10 @@ def _frame_value(obj: object) -> object: # Gated on the wrapper types, so a user model with a `raw` field goes out whole. if isinstance(obj, (AgentChunk, AgentResponse)) and obj.raw is not None: obj = obj.raw + # A failed turn is a 200 with the failure as data, so error_body never + # sees it. Apply the same rule here: only a PublicError's text leaves. + if isinstance(obj, (AgentOutput, SessionSnapshot)) and obj.error is not None: + obj = obj.model_copy(update={'error': client_safe_failure(obj.error)}) return to_jsonable_python(obj, by_alias=True, exclude_none=True) @@ -72,7 +84,11 @@ def _frame(key: str, value: object) -> str: def result_json(result: object) -> str: - """Encode a one-shot result as compact ``{"result": ...}`` JSON, the bytes every adapter sends.""" + """Encode a one-shot result as compact ``{"result": ...}`` JSON, the bytes every adapter sends. + + A failed agent turn's ``error`` keeps its status but only a PublicError's + message; anything else goes out as a generic message for that status. + """ # Same encoding as to_sse frames: aliases, no null model fields. return _dumps({'result': _frame_value(result)}) @@ -95,7 +111,8 @@ async def to_sse(handle: StreamHandle) -> AsyncGenerator[str, None]: If the run fails, it yields one ``data: {"error": ...}`` instead of the rest and logs the failure with Python's logging module (5xx with a traceback, 4xx as a warning). Only a ``PublicError``'s text reaches the client; anything else goes out as - ``Internal Error``. These are the frames ``serve_flow``, + ``Internal Error``. A failed agent turn's ``error`` in the result frame + follows the same rule (see ``result_json``). These are the frames ``serve_flow``, ``handle_genkit_request`` and ``serve_agent`` send. The result goes out as the run returned it. ``ai.generate_stream()``, diff --git a/packages/genkit/tests/genkit/ai/agent_chat_client_test.py b/packages/genkit/tests/genkit/ai/agent_chat_client_test.py index 19324178e..eaa6cdb67 100644 --- a/packages/genkit/tests/genkit/ai/agent_chat_client_test.py +++ b/packages/genkit/tests/genkit/ai/agent_chat_client_test.py @@ -38,7 +38,7 @@ from genkit._ai._agents._types import StateManagement, TurnResult from genkit._ai._json_patch import apply_json_patch from genkit._core._channel import CloseableQueue -from genkit._core._error import ErrorReason, Failure, GenkitError, Interrupt, PublicError +from genkit._core._error import ErrorReason, Failure, GenkitError, Interrupt, PublicError, client_safe_failure from genkit._core._model import ( AgentInit, AgentInput, @@ -1745,8 +1745,11 @@ def _logged_errors(entries: Sequence[Mapping[str, Any]]) -> list[Mapping[str, An @pytest.mark.asyncio -async def test_custom_agent_raising_foreign_error_redacts_message_and_logs_cause() -> None: - """A ValueError's text stays server-side; the caller gets INTERNAL 'internal error'.""" +async def test_custom_agent_raising_foreign_error_keeps_text_and_logs_cause() -> None: + """In process, res.error keeps the ValueError's text; the cause is also logged with its traceback. + + Redaction happens where a served agent writes to HTTP (genkit.web), not here. + """ structlog.reset_defaults() agent = _flaky( Genkit(), @@ -1758,9 +1761,8 @@ async def test_custom_agent_raising_foreign_error_redacts_message_and_logs_cause with capture_logs() as entries: res = await agent.chat().send('please fail now') - err = _assert_failed(res, message='internal error') + err = _assert_failed(res, message='db password=hunter2') assert err.status == 'INTERNAL' - assert 'hunter2' not in err.model_dump_json() errors = _logged_errors(entries) assert len(errors) == 1 assert errors[0]['event'] == "agent 'ordersDb' raised, returning finish_reason=failed" @@ -2388,30 +2390,38 @@ def __init__(self) -> None: ), (GenkitError(status='ABORTED', message='stopped'), 'ABORTED', 'stopped', None), (PublicError('PERMISSION_DENIED', 'table 12 is reserved'), 'PERMISSION_DENIED', 'table 12 is reserved', None), - # An INTERNAL wrapper around a foreign cause hides it, as generate does for a tool. ( GenkitError(status='INTERNAL', message='pos sync failed', cause=ValueError('dsn=pg://admin@10.0.0.4')), 'INTERNAL', - 'internal error', + 'pos sync failed', None, ), - (asyncio.CancelledError(), 'CANCELLED', 'internal error', None), - (TimeoutError('kitchen printer 10.0.0.9 timed out'), 'DEADLINE_EXCEEDED', 'internal error', None), - (asyncio.TimeoutError('kitchen printer 10.0.0.9 timed out'), 'DEADLINE_EXCEEDED', 'internal error', None), - (_ClientResponseError(), 'INTERNAL', 'internal error', None), - (ValueError('db password=hunter2'), 'INTERNAL', 'internal error', None), + (asyncio.CancelledError(), 'CANCELLED', 'Internal failure', None), + (TimeoutError('kitchen printer timed out'), 'DEADLINE_EXCEEDED', 'kitchen printer timed out', None), + (asyncio.TimeoutError('kitchen printer timed out'), 'DEADLINE_EXCEEDED', 'kitchen printer timed out', None), + (_ClientResponseError(), 'INTERNAL', '429, message=Too Many Requests', None), + (ValueError('bad table number'), 'INTERNAL', 'bad table number', None), ], ) def test_to_error_details_classifies_status_like_go( exc: BaseException, status: str, message: str, details: dict[str, Any] | None ) -> None: - """Only a GenkitError names its status and message; anything else is classified and redacted. + """Only a GenkitError names its status; a foreign int ``.status`` (aiohttp's 429) is INTERNAL. - A foreign int ``.status`` (aiohttp's 429) is INTERNAL, and no foreign - exception text reaches the Failure. + The message is the exception's own text, as in JS and Go; genkit.web + redacts it for HTTP callers. """ failure = to_error_details(exc) assert failure.status == status assert failure.message == message assert failure.details == details + + +def test_to_error_details_marks_only_a_public_error_safe_for_the_wire() -> None: + """A PublicError's Failure survives client_safe_failure; a plain GenkitError's text does not.""" + public = to_error_details(PublicError('PERMISSION_DENIED', 'table 12 is reserved')) + private = to_error_details(GenkitError(status='NOT_FOUND', message='no row for key=hunter2')) + + assert client_safe_failure(public) is public + assert client_safe_failure(private) == Failure(status='NOT_FOUND', message='Not Found') diff --git a/packages/genkit/tests/genkit/ai/agent_conformance_test.py b/packages/genkit/tests/genkit/ai/agent_conformance_test.py index 5225bacfc..bab8e813b 100644 --- a/packages/genkit/tests/genkit/ai/agent_conformance_test.py +++ b/packages/genkit/tests/genkit/ai/agent_conformance_test.py @@ -555,13 +555,10 @@ def _register_custom_agents(*, ai: Genkit, agents: dict[str, Agent]) -> None: ) # Raise inside the turn so run() records last_turn_error, then return - # result() so an attached caller gets a graceful failed output. A - # GenkitError, not a bare exception: the spec reads the message back off - # the snapshot, and Python records foreign exception text as 'internal - # error' (the cause goes to the server log). + # result() so an attached caller gets a graceful failed output. async def failing_agent_fn(session_runner: SessionRunner, _ctx: AgentContext) -> AgentResult: async def handle_turn(_inp: AgentInput, _tc: TurnContext) -> TurnResult | None: - raise GenkitError(status='INTERNAL', message='intentional failure') + raise RuntimeError('intentional failure') await session_runner.run(handle_turn) return await session_runner.result() diff --git a/packages/genkit/tests/genkit/ai/agent_detach_test.py b/packages/genkit/tests/genkit/ai/agent_detach_test.py index 08f255db6..4cc4404ee 100644 --- a/packages/genkit/tests/genkit/ai/agent_detach_test.py +++ b/packages/genkit/tests/genkit/ai/agent_detach_test.py @@ -474,9 +474,7 @@ async def handle_turn(_inp: AgentInput, _: TurnContext) -> None: assert snap.status == SnapshotStatus.FAILED assert snap.finish_reason == AgentFinishReason.FAILED assert snap.error is not None - # The RuntimeError's text stays server-side; the snapshot is client-readable. - assert snap.error.status == 'INTERNAL' - assert snap.error.message == 'internal error' + assert 'intentional failure' in (snap.error.message or '') @pytest.mark.asyncio diff --git a/packages/genkit/tests/genkit/ai/exp_agents_import_test.py b/packages/genkit/tests/genkit/ai/exp_agents_import_test.py index b062bfd1c..08ae5e1fb 100644 --- a/packages/genkit/tests/genkit/ai/exp_agents_import_test.py +++ b/packages/genkit/tests/genkit/ai/exp_agents_import_test.py @@ -168,11 +168,7 @@ async def test_exp_genkit_still_generates() -> None: @pytest.mark.asyncio async def test_agent_turn_awaiting_failing_flow_reports_message_without_details() -> None: - """A turn that awaits a flow raising RuntimeError('db rejected') records 'internal error' and no details. - - The flow wraps the RuntimeError as an INTERNAL GenkitError with a foreign - cause, so its text stays server-side, as generate does for a raising tool. - """ + """A turn that awaits a flow raising RuntimeError('db rejected') records that message and no details.""" ai = Genkit() @ai.flow() @@ -193,6 +189,6 @@ async def handle_turn(inp: AgentInput, __: TurnContext) -> TurnResult | None: assert res.finish_reason == AgentFinishReason.FAILED assert res.error is not None - assert res.error.message == 'internal error' + assert res.error.message == 'db rejected' assert res.error.details is None assert res.error.status == 'INTERNAL' diff --git a/packages/genkit/tests/genkit/core/web_test.py b/packages/genkit/tests/genkit/core/web_test.py index da771c904..c1aff9617 100644 --- a/packages/genkit/tests/genkit/core/web_test.py +++ b/packages/genkit/tests/genkit/core/web_test.py @@ -27,6 +27,10 @@ import genkit import genkit.web from genkit import FlowContext, Genkit, PublicError + +# to_error_details and AgentOutput are private: this test pins the served wire shape. +from genkit._ai._agents._runtime import to_error_details # noqa: TID251 +from genkit._core._model import AgentOutput # noqa: TID251 from genkit.plugin_api import Action from genkit.web import error_json, error_sse, read_body, result_json, to_sse, wants_stream @@ -129,6 +133,23 @@ def test_wants_stream_on_event_stream_accept_or_stream_true() -> None: assert wants_stream(accept=None, stream=None) is False +def test_result_json_redacts_a_failed_agent_turn_unless_public() -> None: + """Flask, Django and FastAPI all send result_json, so a failed turn's error leaves the process redacted.""" + # to_error_details is the runtime's own Failure builder; it marks a PublicError. + private = AgentOutput(finish_reason='failed', error=to_error_details(ValueError('db password=hunter2'))) + public = AgentOutput(finish_reason='failed', error=to_error_details(PublicError('NOT_FOUND', 'no order A-17'))) + + assert result_json(private) == ( + '{"result":{"finishReason":"failed","error":{"status":"INTERNAL","message":"Internal Error"}}}' + ) + assert result_json(public) == ( + '{"result":{"finishReason":"failed","error":{"status":"NOT_FOUND","message":"no order A-17"}}}' + ) + # The object itself still carries the text for in-process callers. + assert private.error is not None + assert private.error.message == 'db password=hunter2' + + def test_result_json_encodes_nested_models_by_alias_without_none_fields() -> None: """result_json emits compact camelCase JSON for nested models while preserving plain-dict nulls.""" order_id = uuid.UUID('12345678-1234-5678-1234-567812345678') From a6e6b21cff0e96bc6cfc787fa518249dadee9436 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Tue, 10 Nov 2026 01:32:50 -0600 Subject: [PATCH 4/8] chore(py): silence pyrefly on Failure's private public flag Pydantic's frozen=True guards fields only; private attrs are stored apart and settable. Pyrefly reads _public as a frozen field. --- packages/genkit/src/genkit/_core/_error.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/genkit/src/genkit/_core/_error.py b/packages/genkit/src/genkit/_core/_error.py index e36b37360..d76510f77 100644 --- a/packages/genkit/src/genkit/_core/_error.py +++ b/packages/genkit/src/genkit/_core/_error.py @@ -183,7 +183,9 @@ def reason(self) -> ErrorReason | None: def mark_public_failure(failure: Failure) -> Failure: """Mark ``failure`` as built from a PublicError, so a served agent sends its text.""" - failure._public = True + # frozen=True only guards fields; Pydantic stores private attrs apart and + # lets them be set. Pyrefly reads it as a frozen field. + failure._public = True # pyrefly: ignore[read-only] return failure From ac33b8fa1659da72c3c63c26e9941599b7cf6c2f Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Tue, 10 Nov 2026 16:55:01 -0600 Subject: [PATCH 5/8] fix(py/agents): preserve prompt-agent PublicError on wire and value equality on Failure --- .../tests/agent_handler_test.py | 57 +++++++++++++++++++ .../genkit/src/genkit/_ai/_agents/_runtime.py | 7 +++ packages/genkit/src/genkit/_ai/_generate.py | 6 +- packages/genkit/src/genkit/_core/_error.py | 27 ++++++++- .../tests/genkit/ai/agent_chat_client_test.py | 14 ++++- 5 files changed, 106 insertions(+), 5 deletions(-) diff --git a/packages/genkit-fastapi/tests/agent_handler_test.py b/packages/genkit-fastapi/tests/agent_handler_test.py index c425d299a..eb88e9deb 100644 --- a/packages/genkit-fastapi/tests/agent_handler_test.py +++ b/packages/genkit-fastapi/tests/agent_handler_test.py @@ -434,3 +434,60 @@ async def test_failed_turn_keeps_error_text_in_process_and_in_the_store() -> Non # 3. Over HTTP, getSnapshot sends the generic message. served = client(agent).post('/api/chat/getSnapshot', json={'snapshotId': snapshot_id}) assert served.json()['result']['error'] == {'status': 'INTERNAL', 'message': 'Internal Error'} + + +@pytest.mark.parametrize( + ('tool_exc', 'expected'), + [ + ( + PublicError('PERMISSION_DENIED', 'table 12 is reserved'), + { + 'status': 'PERMISSION_DENIED', + 'message': 'table 12 is reserved', + 'details': {'reason': ErrorReason.TOOL_FAILED.value}, + }, + ), + ( + RuntimeError('allergen db password=hunter2'), + {'status': 'INTERNAL', 'message': 'Internal Error'}, + ), + ], + ids=['public_tool_error', 'private_tool_error'], +) +@pytest.mark.parametrize('stream', [False, True], ids=['json', 'sse']) +def test_prompt_agent_tool_error_preserves_public_error_over_http( + tool_exc: Exception, + expected: dict[str, Any], + stream: bool, +) -> None: + """A prompt agent whose tool raises PublicError sends that sentence over HTTP; private tool crashes redact.""" + ai = Genkit() + pm, _ = define_scripted_model(ai) + + @ai.tool(name='reserve_table') + async def reserve_table(table: int) -> str: # noqa: ARG001 + raise tool_exc + + pm.responses = [ + ModelResponse( + message=Message( + role=Role.MODEL, + content=[Part.from_tool_request('reserve_table', 12, ref='call_1')], + ), + finish_reason=FinishReason.STOP, + ) + ] + agent = ai.define_agent( + name='reservations', + model='scriptedModel', + tools=['reserve_table'], + store=InMemorySessionStore(), + ) + + response = client(agent).post(f'/api/chat?stream={str(stream).lower()}', json={'message': 'book table 12'}) + + assert response.status_code == 200 + result = sse_events(response.text)[-1]['result'] if stream else response.json()['result'] + assert result['finishReason'] == 'failed' + assert result['error'] == expected + assert 'hunter2' not in response.text diff --git a/packages/genkit/src/genkit/_ai/_agents/_runtime.py b/packages/genkit/src/genkit/_ai/_agents/_runtime.py index 7dedee42c..fc78dafbe 100644 --- a/packages/genkit/src/genkit/_ai/_agents/_runtime.py +++ b/packages/genkit/src/genkit/_ai/_agents/_runtime.py @@ -60,6 +60,7 @@ TaskGroupError, attached_cause, interrupt_escape_error, + is_public_failure, mark_public_failure, ) from genkit._core._logger import get_logger @@ -1162,6 +1163,12 @@ 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( + response.error.status or 'INTERNAL', + response.error.message, + details=response.error.details, + ) raise GenkitError( message=response.error.message, status=response.error.status, diff --git a/packages/genkit/src/genkit/_ai/_generate.py b/packages/genkit/src/genkit/_ai/_generate.py index 4400d302f..b685b28fe 100644 --- a/packages/genkit/src/genkit/_ai/_generate.py +++ b/packages/genkit/src/genkit/_ai/_generate.py @@ -80,6 +80,7 @@ PublicError, _StreamingCallbackError, attached_cause, + mark_public_failure, ) from genkit._core._logger import get_logger, is_debug_enabled from genkit._core._middleware import ( @@ -1507,12 +1508,15 @@ def box_from_exc( details['reason'] = reason.value # Failure.details is a JSON object (Go's map[string]any); drop an empty one. failure_details = dict(cast(Mapping[str, Any], details)) if isinstance(details, Mapping) and details else None + failure = Failure(status=status, message=finish_message, details=failure_details) + if not caller_stopped and not pipe_failed and isinstance(exc, PublicError): + mark_public_failure(failure) out = box_dead_turn( response=response, messages=messages, finish_reason=FinishReason.ABORTED if caller_stopped else FinishReason.FAILED, finish_message=finish_message, - error=Failure(status=status, message=finish_message, details=failure_details), + error=failure, request=request, ) if not caller_stopped: diff --git a/packages/genkit/src/genkit/_core/_error.py b/packages/genkit/src/genkit/_core/_error.py index d76510f77..942c172d5 100644 --- a/packages/genkit/src/genkit/_core/_error.py +++ b/packages/genkit/src/genkit/_core/_error.py @@ -180,6 +180,13 @@ def _from_wire(cls, value: object) -> object: def reason(self) -> ErrorReason | None: return error_reason(self.details) + def __eq__(self, other: object) -> bool: + # _public is wire-redaction provenance, not part of the failure value: + # res.error == Failure(...) and snapshot round-trip equality ignore it. + if not isinstance(other, Failure): + return NotImplemented + return (self.status, self.message, self.details) == (other.status, other.message, other.details) + def mark_public_failure(failure: Failure) -> Failure: """Mark ``failure`` as built from a PublicError, so a served agent sends its text.""" @@ -189,18 +196,32 @@ def mark_public_failure(failure: Failure) -> Failure: return failure +def is_public_failure(failure: Failure) -> bool: + """Whether ``failure`` came from a ``PublicError`` in this process.""" + return failure._public + + def client_safe_failure(failure: Failure) -> Failure: """``failure`` as the HTTP caller of a served agent may see it. Same rule as ``error_body`` for a served flow: a PublicError's message - and details go out as is. Anything else keeps its status, since callers - branch on it, but gets a generic message for that status and no + and cleaned details go out as is. Anything else keeps its status, since + callers branch on it, but gets a generic message for that status and no details, so exception text, provider responses and internal ids stay in the process, the store and the server log. Mirrors Go's ``clientSafeError``. """ if failure._public: - return failure + details = _client_details(failure.details) + if details == failure.details: + return failure + return mark_public_failure( + Failure( + status=failure.status, + message=failure.message, + details=details if isinstance(details, dict) else None, + ) + ) status = failure.status message = 'Internal Error' if status is None or status == 'INTERNAL' else status.replace('_', ' ').title() return Failure(status=status, message=message) diff --git a/packages/genkit/tests/genkit/ai/agent_chat_client_test.py b/packages/genkit/tests/genkit/ai/agent_chat_client_test.py index eaa6cdb67..8983bc9aa 100644 --- a/packages/genkit/tests/genkit/ai/agent_chat_client_test.py +++ b/packages/genkit/tests/genkit/ai/agent_chat_client_test.py @@ -2419,9 +2419,21 @@ def test_to_error_details_classifies_status_like_go( def test_to_error_details_marks_only_a_public_error_safe_for_the_wire() -> None: - """A PublicError's Failure survives client_safe_failure; a plain GenkitError's text does not.""" + """A PublicError's Failure survives client_safe_failure; plain errors and deserialized snapshots do not.""" public = to_error_details(PublicError('PERMISSION_DENIED', 'table 12 is reserved')) + public_with_stack = to_error_details( + PublicError('INVALID_ARGUMENT', 'bad seat count', details={'field': 'seats', 'stack': 'Traceback...'}) + ) private = to_error_details(GenkitError(status='NOT_FOUND', message='no row for key=hunter2')) + reloaded = Failure.model_validate_json(public.model_dump_json()) + assert public == Failure(status='PERMISSION_DENIED', message='table 12 is reserved') + assert public == reloaded assert client_safe_failure(public) is public + assert client_safe_failure(public_with_stack) == Failure( + status='INVALID_ARGUMENT', + message='bad seat count', + details={'field': 'seats'}, + ) assert client_safe_failure(private) == Failure(status='NOT_FOUND', message='Not Found') + assert client_safe_failure(reloaded) == Failure(status='PERMISSION_DENIED', message='Permission Denied') From 98f4d6f0691d7099d936fc08c00624f27bb4d278 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Wed, 11 Nov 2026 21:21:00 -0600 Subject: [PATCH 6/8] fix(py/agents): align server failure logging with wire redaction --- .../genkit/src/genkit/_ai/_agents/_runtime.py | 24 ++-- packages/genkit/src/genkit/_ai/_generate.py | 44 ++++--- packages/genkit/src/genkit/_core/_error.py | 25 +++- .../tests/genkit/ai/agent_chat_client_test.py | 114 +++++++++++++++++- 4 files changed, 175 insertions(+), 32 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_agents/_runtime.py b/packages/genkit/src/genkit/_ai/_agents/_runtime.py index fc78dafbe..8e033ee8e 100644 --- a/packages/genkit/src/genkit/_ai/_agents/_runtime.py +++ b/packages/genkit/src/genkit/_ai/_agents/_runtime.py @@ -42,9 +42,9 @@ from genkit._ai._agents._types import ChunkTransform, StateTransform, TurnContext, TurnResult from genkit._ai._generate import ( CallScope, - boxed_finish_message, generate_action, log_dropped_failure, + mark_failure_logged, ) from genkit._ai._json_patch import diff_json from genkit._core._action import ActionRunContext, get_current_context @@ -60,6 +60,7 @@ TaskGroupError, attached_cause, interrupt_escape_error, + is_logged_failure, is_public_failure, mark_public_failure, ) @@ -1169,11 +1170,14 @@ def on_chunk(chunk: ModelResponseChunk) -> None: response.error.message, details=response.error.details, ) - raise GenkitError( + err = GenkitError( message=response.error.message, status=response.error.status, details=response.error.details, ) + if is_logged_failure(response.error): + mark_failure_logged(err) + raise err # Return the turn result wrapping the model finish reason finish_reason = to_agent_finish_reason(response.finish_reason) if response.finish_reason is not None else None @@ -1199,9 +1203,10 @@ def to_error_details(exc: BaseException, *, agent: str | None = None) -> Failure and Go ``convertKeepText``, so in-process callers, the session store and the Dev UI see what went wrong. A served agent's HTTP caller doesn't: ``genkit.web`` swaps in a generic message unless the turn raised a - ``PublicError`` (see ``client_safe_failure``). A cause that generate's - rule for a raising tool would hide is also logged here with its - traceback, so the server log has it when the wire doesn't. + ``PublicError`` (see ``client_safe_failure``). Every non-``PublicError`` + failure (except an escaped ``Interrupt``) is logged here unless + ``generate`` already logged it, so the server log has what the wire + redacts. Args: exc: The exception that ended the turn or invocation. @@ -1214,11 +1219,10 @@ def to_error_details(exc: BaseException, *, agent: str | None = None) -> Failure message = exc.message cause = attached_cause(exc) # interrupt_escape_error's sentence isn't foreign text: the attached - # Interrupt is tool metadata. A prompt agent re-raises generate's - # already-boxed failure as a fresh GenkitError carrying - # ``internal error``; generate logged that cause already. + # Interrupt is tool metadata. A prompt agent stamps mark_failure_logged + # on the GenkitError it re-raises when generate already logged it. escaped_interrupt = cause is not None and interrupt_escape_error(cause) is not None - hides_cause = not escaped_interrupt and boxed_finish_message(exc=exc, pipe_failed=False) != exc.message + hides_cause = not isinstance(exc, PublicError) and not escaped_interrupt if isinstance(exc.details, Mapping) and exc.details: details = dict(cast(Mapping[str, Any], exc.details)) else: @@ -1232,7 +1236,7 @@ def to_error_details(exc: BaseException, *, agent: str | None = None) -> Failure message = str(exc) or 'Internal failure' hides_cause = True if hides_cause: - log_dropped_failure(exc, agent=agent) + log_dropped_failure(exc, agent=agent, redacted=True) failure = Failure(status=status, message=message, details=details) if isinstance(exc, PublicError): mark_public_failure(failure) diff --git a/packages/genkit/src/genkit/_ai/_generate.py b/packages/genkit/src/genkit/_ai/_generate.py index b685b28fe..eb178f0f4 100644 --- a/packages/genkit/src/genkit/_ai/_generate.py +++ b/packages/genkit/src/genkit/_ai/_generate.py @@ -80,6 +80,7 @@ PublicError, _StreamingCallbackError, attached_cause, + mark_logged_failure, mark_public_failure, ) from genkit._core._logger import get_logger, is_debug_enabled @@ -1369,24 +1370,31 @@ def boxed_finish_message(*, exc: BaseException, pipe_failed: bool) -> str: return INTERNAL_FINISH_MESSAGE -# Set on an exception once log_dropped_failure has logged it, so the tool site -# and the generate-level box never log the same failure twice. +# Set on an exception once log_dropped_failure has logged it, so the tool site, +# the generate-level box, and an outer agent never log the same failure twice. _LOGGED_ATTR = '_genkit_failure_logged' +def mark_failure_logged(exc: BaseException) -> None: + """Stamp ``exc`` as already logged so an outer handler skips it.""" + with contextlib.suppress(AttributeError, TypeError): + setattr(exc, _LOGGED_ATTR, True) + + def log_dropped_failure( exc: BaseException, *, model: str | None = None, tool: str | None = None, agent: str | None = None, -) -> None: - """Log a failure whose cause boxing hides behind ``internal error``. + redacted: bool = False, +) -> bool: + """Log a failure whose cause boxing or the agent wire hides. - The caller only gets ``finish_reason=failed`` with ``internal error``, so - without this line the cause lives only in an exported trace. Failures that - keep their own message (``PublicError``, a ``GenkitError`` without a - foreign cause) are already on ``response.error`` and are not logged. + ``generate`` only hides failures that collapse to ``internal error``; a + served agent's wire (``client_safe_failure``) hides every non-``PublicError`` + message and passes ``redacted=True``. Returns True once ``exc`` has been + logged (on this call or an earlier inner one). Args: exc: The exception about to be boxed. @@ -1394,13 +1402,14 @@ def log_dropped_failure( tool: Tool that raised, when known. Named over ``model``. agent: Agent whose turn raised, when known. ``tool`` and ``model`` are named over it. + redacted: Caller's boundary hides ``exc`` even when ``generate``'s + in-process finish message would keep its text. """ if getattr(exc, _LOGGED_ATTR, False): - return - if boxed_finish_message(exc=exc, pipe_failed=False) != INTERNAL_FINISH_MESSAGE: - return - with contextlib.suppress(AttributeError, TypeError): - setattr(exc, _LOGGED_ATTR, True) + return True + if not redacted and boxed_finish_message(exc=exc, pipe_failed=False) != INTERNAL_FINISH_MESSAGE: + return False + mark_failure_logged(exc) fields: dict[str, object] = {} if model: fields['model'] = model @@ -1418,8 +1427,9 @@ def log_dropped_failure( elif agent: culprit = f'agent {agent!r}' else: - culprit = 'generate' + culprit = 'agent' if redacted else 'generate' logger.error('%s raised, returning finish_reason=failed', culprit, exc_info=exc, **fields) + return True def stamp_cancelled_error( @@ -1481,14 +1491,16 @@ def box_from_exc( """Box a failure after generate has entered: closed history, unanswered turn dropped.""" callback_cause = streaming_callback_cause(exc=exc) pipe_failed = False + logged = bool(getattr(exc, _LOGGED_ATTR, False)) if callback_cause is not None: # The stream pipe is framework plumbing, not a tool or model # sentinel. Keep the sink's wording; replace any loop reason. exc = callback_cause reason = ErrorReason.STREAM_CALLBACK_FAILED pipe_failed = True + logged = False elif not caller_stopped: - log_dropped_failure(exc, model=model) + logged = log_dropped_failure(exc, model=model) finish_message = boxed_finish_message(exc=exc, pipe_failed=pipe_failed) if caller_stopped: finish_message = 'Generation aborted.' @@ -1511,6 +1523,8 @@ def box_from_exc( failure = Failure(status=status, message=finish_message, details=failure_details) if not caller_stopped and not pipe_failed and isinstance(exc, PublicError): mark_public_failure(failure) + if logged: + mark_logged_failure(failure) out = box_dead_turn( response=response, messages=messages, diff --git a/packages/genkit/src/genkit/_core/_error.py b/packages/genkit/src/genkit/_core/_error.py index 942c172d5..4c55b2636 100644 --- a/packages/genkit/src/genkit/_core/_error.py +++ b/packages/genkit/src/genkit/_core/_error.py @@ -153,6 +153,9 @@ class Failure(_RuntimeErrorWire): # its message. Not serialized, like Go's status.Error.Public: a failure # read back from a store or another process is redacted on the wire. _public: bool = PrivateAttr(default=False) + # Set when generate already logged the underlying exception, so a prompt + # agent re-raising response.error does not log it a second time. + _logged: bool = PrivateAttr(default=False) @model_validator(mode='before') @classmethod @@ -181,11 +184,12 @@ def reason(self) -> ErrorReason | None: return error_reason(self.details) def __eq__(self, other: object) -> bool: - # _public is wire-redaction provenance, not part of the failure value: - # res.error == Failure(...) and snapshot round-trip equality ignore it. + # Private attrs (_public, _logged) live in __pydantic_private__, not + # __dict__: res.error == Failure(...) and snapshot round-trip equality + # compare all declared fields and ignore provenance. if not isinstance(other, Failure): return NotImplemented - return (self.status, self.message, self.details) == (other.status, other.message, other.details) + return self.__dict__ == other.__dict__ def mark_public_failure(failure: Failure) -> Failure: @@ -201,6 +205,17 @@ def is_public_failure(failure: Failure) -> bool: return failure._public +def mark_logged_failure(failure: Failure) -> Failure: + """Mark ``failure`` as already logged server-side by ``generate``.""" + failure._logged = True # pyrefly: ignore[read-only] + return failure + + +def is_logged_failure(failure: Failure) -> bool: + """Whether ``generate`` already logged the exception behind ``failure``.""" + return failure._logged + + def client_safe_failure(failure: Failure) -> Failure: """``failure`` as the HTTP caller of a served agent may see it. @@ -209,7 +224,9 @@ def client_safe_failure(failure: Failure) -> Failure: callers branch on it, but gets a generic message for that status and no details, so exception text, provider responses and internal ids stay in the process, the store and the server log. Mirrors Go's - ``clientSafeError``. + ``clientSafeError``, except ``GENKIT_ENV=dev`` still redacts here + (matching ``error_body``; the Dev UI reads unredacted errors over + reflection). """ if failure._public: details = _client_details(failure.details) diff --git a/packages/genkit/tests/genkit/ai/agent_chat_client_test.py b/packages/genkit/tests/genkit/ai/agent_chat_client_test.py index 8983bc9aa..b6cccb0b0 100644 --- a/packages/genkit/tests/genkit/ai/agent_chat_client_test.py +++ b/packages/genkit/tests/genkit/ai/agent_chat_client_test.py @@ -38,7 +38,15 @@ from genkit._ai._agents._types import StateManagement, TurnResult from genkit._ai._json_patch import apply_json_patch from genkit._core._channel import CloseableQueue -from genkit._core._error import ErrorReason, Failure, GenkitError, Interrupt, PublicError, client_safe_failure +from genkit._core._error import ( + ErrorReason, + Failure, + GenkitError, + Interrupt, + PublicError, + client_safe_failure, + mark_logged_failure, +) from genkit._core._model import ( AgentInit, AgentInput, @@ -1634,7 +1642,7 @@ def _flaky( *, store: InMemorySessionStore | None, reply: Message | None = None, - fail: Exception | None = None, + fail: BaseException | None = None, ) -> Agent: """'fail' raises, 'block' is blocked, 'pause' interrupts, anything else replies.""" boom = fail or GenkitError(status='INTERNAL', message='boom') @@ -1772,7 +1780,7 @@ async def test_custom_agent_raising_foreign_error_keeps_text_and_logs_cause() -> @pytest.mark.asyncio async def test_custom_agent_raising_genkit_error_keeps_status_and_message() -> None: - """A GenkitError is the author's chosen caller-facing failure, so it passes through unlogged.""" + """In process, res.error keeps status and message; the server logs once since HTTP redacts non-PublicError.""" structlog.reset_defaults() agent = _flaky( Genkit(), @@ -1786,6 +1794,59 @@ async def test_custom_agent_raising_genkit_error_keeps_status_and_message() -> N err = _assert_failed(res, message='no order A-17') assert err.status == 'NOT_FOUND' + errors = _logged_errors(entries) + assert len(errors) == 1 + assert errors[0]['agent'] == 'orderLookup' + assert 'no order A-17' in str(errors[0]['exc_info']) + + +@pytest.mark.asyncio +async def test_custom_agent_raising_internal_genkit_error_logs_once() -> None: + """A custom turn raising GenkitError(INTERNAL) without a cause still logs once since HTTP redacts it.""" + structlog.reset_defaults() + agent = _flaky( + Genkit(), + 'ordersDb', + store=InMemorySessionStore(), + fail=GenkitError(status='INTERNAL', message='db password=hunter2'), + ) + + with capture_logs() as entries: + res = await agent.chat().send('please fail now') + + err = _assert_failed(res, message='db password=hunter2') + assert err.status == 'INTERNAL' + errors = _logged_errors(entries) + assert len(errors) == 1 + assert errors[0]['agent'] == 'ordersDb' + assert 'db password=hunter2' in str(errors[0]['exc_info']) + + +@pytest.mark.asyncio +async def test_custom_agent_raising_public_error_or_escaped_interrupt_is_not_logged() -> None: + """PublicError reaches HTTP unredacted and escaped Interrupt is tool metadata; neither logs as dropped.""" + structlog.reset_defaults() + public_agent = _flaky( + Genkit(), + 'orderLookup', + store=InMemorySessionStore(), + fail=PublicError('NOT_FOUND', 'no order A-17'), + ) + interrupt_agent = _flaky( + Genkit(), + 'badPause', + store=InMemorySessionStore(), + fail=Interrupt({'step': 'confirm'}), + ) + + with capture_logs() as entries: + public_res = await public_agent.chat().send('please fail now') + intr_res = await interrupt_agent.chat().send('please fail now') + + public_err = _assert_failed(public_res, message='no order A-17') + assert public_err.status == 'NOT_FOUND' + intr_err = _assert_failed(intr_res, message='Interrupt raised outside a tool') + assert intr_err.status == 'INTERNAL' assert _logged_errors(entries) == [] @@ -1821,6 +1882,49 @@ async def check_allergens(_: dict) -> str: # noqa: ARG001 assert errors[0]['tool'] == 'check_allergens' +@pytest.mark.asyncio +async def test_prompt_agent_tool_genkit_error_logs_once_and_public_error_skips_log() -> None: + """A tool's plain GenkitError wasn't logged by generate, so the agent logs it once; a PublicError is not logged.""" + structlog.reset_defaults() + ai = Genkit() + pm, _ = define_scripted_model(ai) + mode = 'private' + + @ai.tool(name='check_allergens') + async def check_allergens(_: dict) -> str: # noqa: ARG001 + if mode == 'public': + raise PublicError('INVALID_ARGUMENT', 'we do not serve peanuts') + raise GenkitError(status='NOT_FOUND', message='secret row missing') + + tool_call = ModelResponse( + message=Message( + role=Role.MODEL, + content=[Part(tool_request=ToolRequest(name='check_allergens', input={}, ref='1'))], + ), + finish_reason=FinishReason.STOP, + ) + pm.responses = [tool_call, tool_call] + agent = ai.define_agent(name='allergyAgent', model='scriptedModel', tools=['check_allergens']) + + with capture_logs() as private_entries: + private_res = await agent.chat().send('is the tartine nut-free?') + + private_err = _assert_failed(private_res, message='secret row missing') + assert private_err.status == 'NOT_FOUND' + private_errors = _logged_errors(private_entries) + assert len(private_errors) == 1 + assert private_errors[0]['agent'] == 'allergyAgent' + assert 'secret row missing' in str(private_errors[0]['exc_info']) + + mode = 'public' + with capture_logs() as public_entries: + public_res = await agent.chat().send('what about peanut satay?') + + public_err = _assert_failed(public_res, message='we do not serve peanuts') + assert public_err.status == 'INVALID_ARGUMENT' + assert _logged_errors(public_entries) == [] + + @pytest.mark.asyncio async def test_send_on_failed_turn_keeps_last_good_snapshot_id() -> None: """res.snapshot_id and chat.snapshot_id both stay on the last completed snapshot.""" @@ -2429,6 +2533,10 @@ def test_to_error_details_marks_only_a_public_error_safe_for_the_wire() -> None: assert public == Failure(status='PERMISSION_DENIED', message='table 12 is reserved') assert public == reloaded + assert mark_logged_failure(Failure(status='INTERNAL', message='internal error')) == Failure( + status='INTERNAL', + message='internal error', + ) assert client_safe_failure(public) is public assert client_safe_failure(public_with_stack) == Failure( status='INVALID_ARGUMENT', From 34c264627854891b38430d5d46a4d0a9841af2dd Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Wed, 11 Nov 2026 22:12:01 -0600 Subject: [PATCH 7/8] fix(py/agents): keep caller-facing snapshot/resume errors public and redact stored snapshots --- .../tests/agent_handler_test.py | 245 +++++++++++++++++- .../genkit/src/genkit/_ai/_agents/_base.py | 29 ++- .../genkit/src/genkit/_ai/_agents/_runtime.py | 25 +- .../_session_stores/_inmemory_store.py | 29 ++- .../src/genkit/_ai/_agents/_snapshot.py | 18 +- packages/genkit/src/genkit/_ai/_generate.py | 18 +- packages/genkit/src/genkit/_core/_error.py | 13 +- .../genkit/tests/genkit/core/error_test.py | 22 ++ .../typecheck/init_kwonly_contract_test.py | 12 +- 9 files changed, 358 insertions(+), 53 deletions(-) diff --git a/packages/genkit-fastapi/tests/agent_handler_test.py b/packages/genkit-fastapi/tests/agent_handler_test.py index eb88e9deb..06b38d783 100644 --- a/packages/genkit-fastapi/tests/agent_handler_test.py +++ b/packages/genkit-fastapi/tests/agent_handler_test.py @@ -9,6 +9,7 @@ import json import logging import re +from pathlib import Path from typing import Any import pytest @@ -20,8 +21,10 @@ from genkit import ( ErrorReason, + Failure, FinishReason, GenkitError, + Interrupt, Message, ModelResponse, ModelResponseChunk, @@ -30,23 +33,26 @@ Role, ) -# error_from_http is private: this test pins the client-side HTTP error mapping. -from genkit._ai._agents._client import error_from_http # noqa: TID251 +# error_from_http / error_from_wire are private: this test pins client-side HTTP error mapping. +from genkit._ai._agents._client import error_from_http, error_from_wire # noqa: TID251 from genkit.exp import Genkit from genkit.exp.agent import ( AgentContext, AgentInit, AgentInput, AgentResult, + FileSessionStore, InMemorySessionStore, SessionRunner, + SessionSnapshot, + SessionState, SnapshotStatus, TurnContext, TurnResult, ) from genkit.plugin_api import provider_error from genkit.testing import define_scripted_model -from genkit.web import to_sse +from genkit.web import error_json, to_sse def build_agent(name: str, *, server_managed: bool = True) -> Any: @@ -491,3 +497,236 @@ async def reserve_table(table: int) -> str: # noqa: ARG001 assert result['finishReason'] == 'failed' assert result['error'] == expected assert 'hunter2' not in response.text + + +@pytest.mark.parametrize('stream', [False, True], ids=['json', 'sse']) +def test_missing_snapshot_id_over_http_returns_public_error_with_reason(stream: bool) -> None: + """A stale snapshotId returns a 200 failed turn whose message and SNAPSHOT_NOT_FOUND reason survive HTTP.""" + agent = build_agent('ordersAgent') + body = { + 'data': {'message': {'role': 'user', 'content': [{'text': 'status?'}]}}, + 'init': {'snapshotId': 'snap-missing'}, + } + + response = client(agent).post(f'/api/chat?stream={str(stream).lower()}', json=body) + + assert response.status_code == 200 + result = sse_events(response.text)[-1]['result'] if stream else response.json()['result'] + assert result['finishReason'] == 'failed' + assert result['error'] == { + 'status': 'NOT_FOUND', + 'message': "Snapshot 'snap-missing' not found", + 'details': {'reason': 'SNAPSHOT_NOT_FOUND'}, + } + assert Failure.model_validate(result['error']).reason is ErrorReason.SNAPSHOT_NOT_FOUND + assert error_from_wire(result['error']).reason is ErrorReason.SNAPSHOT_NOT_FOUND + + thrown_body = error_json( + PublicError('NOT_FOUND', "Snapshot 'snap-missing' not found", reason=ErrorReason.SNAPSHOT_NOT_FOUND) + ) + assert error_from_http(status_code=404, body=thrown_body).reason is ErrorReason.SNAPSHOT_NOT_FOUND + + +@pytest.mark.asyncio +@pytest.mark.parametrize('stream', [False, True], ids=['json', 'sse']) +async def test_non_resumable_snapshot_over_http_returns_public_error_with_reason(stream: bool) -> None: + """Resuming a failed snapshot by snapshotId over HTTP keeps SNAPSHOT_NOT_RESUMABLE on error.details.""" + ai = Genkit() + store: InMemorySessionStore[Any] = InMemorySessionStore() + define_scripted_model( + ai, + name='scriptedModel', + responses=[ + ModelResponse( + finish_reason=FinishReason.STOP, + message=Message(role=Role.MODEL, content=[Part.from_text('ok')]), + ) + ], + ) + ai.define_prompt(name='ordersAgent', model='scriptedModel', system='You echo things.') + agent = ai.define_prompt_agent(name='ordersAgent', store=store) + + failed_row = SessionSnapshot( + snapshot_id='snap-failed', + session_id='sess-1', + created_at='2026-06-18T12:00:00Z', + status=SnapshotStatus.FAILED, + state=SessionState(session_id='sess-1', messages=[], artifacts=[]), + ) + await store.save_snapshot(failed_row.snapshot_id, lambda _existing: failed_row) + + body = { + 'data': {'message': {'role': 'user', 'content': [{'text': 'continue'}]}}, + 'init': {'snapshotId': 'snap-failed'}, + } + response = client(agent).post(f'/api/chat?stream={str(stream).lower()}', json=body) + + assert response.status_code == 200 + result = sse_events(response.text)[-1]['result'] if stream else response.json()['result'] + assert result['finishReason'] == 'failed' + err = result['error'] + assert err['status'] == 'INVALID_ARGUMENT' + assert "Snapshot 'snap-failed' is not resumable" in err['message'] + assert err['details'] == {'reason': 'SNAPSHOT_NOT_RESUMABLE'} + assert Failure.model_validate(err).reason is ErrorReason.SNAPSHOT_NOT_RESUMABLE + + +def test_invalid_resume_and_unresolved_tool_request_over_http_keep_reason() -> None: + """Caller resume mistakes return PublicError text and INVALID_RESUME / UNRESOLVED_TOOL_REQUEST over HTTP.""" + ai = Genkit() + pm, _ = define_scripted_model(ai) + + @ai.tool(name='approve_refund') + async def approve_refund(order_id: str) -> str: + raise Interrupt({'order_id': order_id}) + + pm.responses = [ + ModelResponse( + finish_reason=FinishReason.STOP, + message=Message(role=Role.MODEL, content=[Part.from_text('How can I help?')]), + ), + ModelResponse( + finish_reason=FinishReason.STOP, + message=Message( + role=Role.MODEL, + content=[Part.from_tool_request('approve_refund', 'A-17', ref='call_1')], + ), + ), + ] + agent = ai.define_agent( + name='refunds', + model='scriptedModel', + tools=['approve_refund'], + store=InMemorySessionStore(), + ) + http = client(agent) + + # 1. Complete a plain text turn, then try to resume an unknown tool response and an empty resume. + first = http.post('/api/chat', json={'message': 'hi'}).json()['result'] + snap_1 = first['snapshotId'] + + bad_ref = http.post( + '/api/chat', + json={ + 'data': { + 'resume': { + 'respond': [{'toolResponse': {'name': 'approve_refund', 'ref': 'bogus', 'output': 'ok'}}], + } + }, + 'init': {'snapshotId': snap_1}, + }, + ).json()['result'] + assert bad_ref['finishReason'] == 'failed' + assert bad_ref['error']['status'] == 'INVALID_ARGUMENT' + assert "resume.respond references tool 'approve_refund'" in bad_ref['error']['message'] + assert bad_ref['error']['details'] == {'reason': 'INVALID_RESUME'} + + no_tool_turn = http.post( + '/api/chat', + json={'data': {'resume': {'metadata': {'by': 'caller'}}}, 'init': {'snapshotId': snap_1}}, + ).json()['result'] + assert no_tool_turn['finishReason'] == 'failed' + assert no_tool_turn['error']['status'] == 'FAILED_PRECONDITION' + assert "Cannot 'resume' generation" in no_tool_turn['error']['message'] + assert no_tool_turn['error']['details'] == {'reason': 'INVALID_RESUME'} + + # 2. Pause on an interrupt, then send a resume that omits the interrupted tool request. + paused = http.post( + '/api/chat', + json={ + 'data': {'message': {'role': 'user', 'content': [{'text': 'refund A-17'}]}}, + 'init': {'snapshotId': snap_1}, + }, + ).json()['result'] + assert paused['finishReason'] == 'interrupted' + + unresolved = http.post( + '/api/chat', + json={'data': {'resume': {'metadata': {'by': 'caller'}}}, 'init': {'snapshotId': paused['snapshotId']}}, + ).json()['result'] + assert unresolved['finishReason'] == 'failed' + assert unresolved['error']['status'] == 'INVALID_ARGUMENT' + assert "Unresolved tool request 'approve_refund'" in unresolved['error']['message'] + assert unresolved['error']['details'] == {'reason': 'UNRESOLVED_TOOL_REQUEST'} + + +@pytest.mark.asyncio +async def test_private_tool_failure_keeps_reason_in_process_but_strips_details_over_http() -> None: + """A non-public TOOL_FAILED failure exposes .reason in process, while HTTP omits details.""" + ai = Genkit() + pm, _ = define_scripted_model(ai) + + @ai.tool(name='charge_card') + async def charge_card(amount: int) -> str: # noqa: ARG001 + raise RuntimeError('gateway key=sk_live_hunter2') + + call_msg = ModelResponse( + message=Message( + role=Role.MODEL, + content=[Part.from_tool_request('charge_card', 42, ref='call_1')], + ), + finish_reason=FinishReason.STOP, + ) + pm.responses = [call_msg, call_msg] + agent = ai.define_agent( + name='billing', + model='scriptedModel', + tools=['charge_card'], + store=InMemorySessionStore(), + ) + + in_proc = await agent.chat().send('charge $42') + assert in_proc.error is not None + assert in_proc.error.reason is ErrorReason.TOOL_FAILED + + http_res = client(agent).post('/api/chat', json={'message': 'charge $42'}).json()['result'] + assert http_res['finishReason'] == 'failed' + assert http_res['error'] == {'status': 'INTERNAL', 'message': 'Internal Error'} + assert 'details' not in http_res['error'] + + +@pytest.mark.asyncio +@pytest.mark.parametrize('store_kind', ['memory', 'file']) +async def test_detached_public_error_redacts_on_http_get_snapshot_across_stores( + store_kind: str, + tmp_path: Path, +) -> None: + """Direct HTTP turns keep PublicError text; stored snapshots read via HTTP getSnapshot redact across all stores.""" + ai = Genkit() + store: Any = InMemorySessionStore() if store_kind == 'memory' else FileSessionStore(str(tmp_path)) + + async def fn(session_runner: SessionRunner, _ctx: AgentContext) -> AgentResult: + async def turn(_inp: AgentInput, _tc: TurnContext) -> TurnResult | None: + raise PublicError('PERMISSION_DENIED', 'table 12 is reserved') + + await session_runner.run(turn) + return await session_runner.result() + + agent = ai.define_custom_agent(name='reservations', fn=fn, store=store) + http = client(agent) + + # 1. Direct non-detached HTTP turn still returns the PublicError text. + live = http.post('/api/chat', json={'message': 'book table 12'}).json()['result'] + assert live['finishReason'] == 'failed' + assert live['error'] == {'status': 'PERMISSION_DENIED', 'message': 'table 12 is reserved'} + + # 2. Detached turn persists the failure; in-process keeps the text, HTTP getSnapshot redacts it. + out = await agent.run( + input=AgentInput(message=Message(role=Role.USER, content=[Part.from_text('book table 12')]), detach=True), + init=AgentInit(), + ) + snapshot_id = out.response.snapshot_id + assert snapshot_id is not None + for _ in range(200): + snap = await agent.get_snapshot_data(snapshot_id=snapshot_id) + if snap is not None and snap.status == SnapshotStatus.FAILED: + break + await asyncio.sleep(0.01) + else: + raise AssertionError('detached turn never finalized') + + assert snap.error is not None + assert snap.error.message == 'table 12 is reserved' + + served = http.post('/api/chat/getSnapshot', json={'snapshotId': snapshot_id}).json()['result'] + assert served['error'] == {'status': 'PERMISSION_DENIED', 'message': 'Permission Denied'} diff --git a/packages/genkit/src/genkit/_ai/_agents/_base.py b/packages/genkit/src/genkit/_ai/_agents/_base.py index 2758423f7..3371c544b 100644 --- a/packages/genkit/src/genkit/_ai/_agents/_base.py +++ b/packages/genkit/src/genkit/_ai/_agents/_base.py @@ -68,7 +68,7 @@ render_prompt, ) from genkit._core._action import Action, ActionKind, BidiAction, BidiFn, get_current_context -from genkit._core._error import ErrorReason, GenkitError +from genkit._core._error import ErrorReason, GenkitError, PublicError from genkit._core._middleware import Middleware from genkit._core._model import ( AgentInit, @@ -311,9 +311,9 @@ async def snapshot_fn(req: GetSnapshotRequest) -> SessionSnapshot: # an empty-but-successful read, so surface it as NOT_FOUND instead of a # null the caller has to re-interpret. target = sid or sess_id or 'unknown' - raise GenkitError( - status='NOT_FOUND', - message=f'Snapshot {target!r} not found for agent {name!r}.', + raise PublicError( + 'NOT_FOUND', + f'Snapshot {target!r} not found for agent {name!r}.', reason=ErrorReason.SNAPSHOT_NOT_FOUND, ) return snap @@ -507,21 +507,23 @@ def ref_suffix(ref: str | None) -> str: continue match = find(tr.name, tr.ref) if match is None: - raise GenkitError( - status='INVALID_ARGUMENT', - message=( + raise PublicError( + 'INVALID_ARGUMENT', + ( f"resume.restart references tool '{tr.name}'{ref_suffix(tr.ref)} " 'which was not found in session history.' ), + reason=ErrorReason.INVALID_RESUME, ) if tool_input_key(tr.input) != tool_input_key(match.input): - raise GenkitError( - status='INVALID_ARGUMENT', - message=( + raise PublicError( + 'INVALID_ARGUMENT', + ( f"resume.restart for tool '{tr.name}'{ref_suffix(tr.ref)} has modified inputs that do not " 'match the original tool request in session history. Restart inputs must exactly match the ' 'interrupted tool request.' ), + reason=ErrorReason.INVALID_RESUME, ) for respond_part in resume.respond or []: @@ -529,10 +531,11 @@ def ref_suffix(ref: str | None) -> str: if resp is None: continue if find(resp.name, resp.ref) is None: - raise GenkitError( - status='INVALID_ARGUMENT', - message=( + raise PublicError( + 'INVALID_ARGUMENT', + ( f"resume.respond references tool '{resp.name}'{ref_suffix(resp.ref)} " 'which was not found in session history.' ), + reason=ErrorReason.INVALID_RESUME, ) diff --git a/packages/genkit/src/genkit/_ai/_agents/_runtime.py b/packages/genkit/src/genkit/_ai/_agents/_runtime.py index 8e033ee8e..66e01559c 100644 --- a/packages/genkit/src/genkit/_ai/_agents/_runtime.py +++ b/packages/genkit/src/genkit/_ai/_agents/_runtime.py @@ -329,9 +329,9 @@ class AgentInitError(PublicError): Covers calling an agent with an init that does not match its state-management mode (e.g. sending ``state`` to a server-managed agent). Recoverable pre-turn - problems (missing snapshot, non-resumable snapshot, invalid custom state) - stay as plain ``GenkitError`` so the caller can absorb them into - ``finish_reason='failed'``. + problems (missing or non-resumable snapshot, invalid custom state) are not + subclasses of ``AgentInitError``, so ``define_custom_agent`` absorbs them + into ``finish_reason='failed'``. It is a ``PublicError``: the message names only the init fields and ids the caller sent, so a served agent returns its status, message, and @@ -347,7 +347,7 @@ def __init__(self, *, status: StatusName, message: str, reason: ErrorReason | No message: Caller-facing sentence; must not include server-side data. reason: Stable reason, sent on the wire as ``details.reason``. """ - super().__init__(status, message, details={'reason': reason.value} if reason is not None else None) + super().__init__(status, message, reason=reason) def seeded_init_fields(state: SessionState) -> str: @@ -418,8 +418,9 @@ async def load_session( client is validated against it before the session is built. State-management mismatches raise ``AgentInitError`` (must propagate). - Missing/non-resumable snapshots and invalid custom state raise plain - ``GenkitError`` for the caller to turn into ``finish_reason='failed'``. + Missing/non-resumable snapshots raise ``PublicError`` and invalid custom + state raises ``GenkitError``; the agent boundary turns both into + ``finish_reason='failed'``. """ name = agent_name or 'agent' @@ -430,9 +431,9 @@ async def load_session( if store is not None and init.snapshot_id: snap = await store.get_snapshot(snapshot_id=init.snapshot_id, context=ctx) if snap is None: - raise GenkitError( - status='NOT_FOUND', - message=f'Snapshot {init.snapshot_id!r} not found', + raise PublicError( + 'NOT_FOUND', + f'Snapshot {init.snapshot_id!r} not found', reason=ErrorReason.SNAPSHOT_NOT_FOUND, ) # When init carries both ids, the snapshot id picks the row and the @@ -450,9 +451,9 @@ async def load_session( # A failed/aborted/pending snapshot is kept for inspection but isn't a # valid place to continue a conversation from. if snap.status != SnapshotStatus.COMPLETED: - raise GenkitError( - status='INVALID_ARGUMENT', - message=( + raise PublicError( + 'INVALID_ARGUMENT', + ( f'Snapshot {init.snapshot_id!r} is not resumable ' f'(status: {snap.status.value if snap.status else "unknown"}). ' "Only 'completed' snapshots can be resumed." diff --git a/packages/genkit/src/genkit/_ai/_agents/_session_stores/_inmemory_store.py b/packages/genkit/src/genkit/_ai/_agents/_session_stores/_inmemory_store.py index aefa2a4e2..feee774df 100644 --- a/packages/genkit/src/genkit/_ai/_agents/_session_stores/_inmemory_store.py +++ b/packages/genkit/src/genkit/_ai/_agents/_session_stores/_inmemory_store.py @@ -39,9 +39,26 @@ session_id_of, subscribe, ) +from genkit._core._error import Failure from genkit._core._model import SessionSnapshot +def _copy_snapshot(snap: SessionSnapshot) -> SessionSnapshot: + """Deep-copy ``snap`` without in-process ``Failure`` provenance, matching JSON stores.""" + copied = snap.model_copy(deep=True) + if copied.error is not None: + copied = copied.model_copy( + update={ + 'error': Failure( + status=copied.error.status, + message=copied.error.message, + details=copied.error.details, + ) + } + ) + return copied + + class InMemorySessionStore(SessionStoreLock, SessionStore[StateT], SnapshotSubscriber, Generic[StateT]): """In-memory snapshot store. State is lost when the process exits.""" @@ -69,12 +86,12 @@ async def get_snapshot( async with self.lock: if snapshot_id is not None: snap = self.snapshots.get(snapshot_id) - return snap.model_copy(deep=True) if snap is not None else None + return _copy_snapshot(snap) if snap is not None else None assert session_id is not None owned = [snap for snap in self.snapshots.values() if session_id_of(snap) == session_id] leaf = select_leaf(snapshots=owned, session_id=session_id, reject_ambiguous=self.reject_ambiguous) - return leaf.model_copy(deep=True) if leaf is not None else None + return _copy_snapshot(leaf) if leaf is not None else None async def save_snapshot( self, @@ -87,10 +104,14 @@ async def save_snapshot( _ = context async with self.lock: existing = self.snapshots.get(snapshot_id) - next_snapshot = apply_save(existing=existing, snapshot_id=snapshot_id, fn=fn) + next_snapshot = apply_save( + existing=_copy_snapshot(existing) if existing is not None else None, + snapshot_id=snapshot_id, + fn=fn, + ) if next_snapshot is None: return None - self.snapshots[next_snapshot.snapshot_id] = next_snapshot.model_copy(deep=True) + self.snapshots[next_snapshot.snapshot_id] = _copy_snapshot(next_snapshot) notify(subs=self.subs, snapshot_id=next_snapshot.snapshot_id, status=next_snapshot.status) return next_snapshot diff --git a/packages/genkit/src/genkit/_ai/_agents/_snapshot.py b/packages/genkit/src/genkit/_ai/_agents/_snapshot.py index dde8efef2..451d84250 100644 --- a/packages/genkit/src/genkit/_ai/_agents/_snapshot.py +++ b/packages/genkit/src/genkit/_ai/_agents/_snapshot.py @@ -24,7 +24,7 @@ from genkit._ai._agents._session import SessionStore from genkit._ai._agents._types import StateTransform from genkit._core._action import get_current_context -from genkit._core._error import ErrorReason, GenkitError +from genkit._core._error import ErrorReason, GenkitError, PublicError from genkit._core._model import SessionSnapshot from genkit._core._typing import SnapshotStatus @@ -71,21 +71,21 @@ def parse_snapshot_lookup_kw( ) -> tuple[str | None, str | None]: """Require exactly one of ``snapshot_id`` or ``session_id``. - A bad selector is a caller mistake, so it raises ``INVALID_ARGUMENT`` — over a - transport that surfaces as a 400, not a 500 the way a bare ``ValueError`` would. + A bad selector is a caller mistake, so it raises ``PublicError`` + ``INVALID_ARGUMENT`` — over a transport that surfaces as a 400, not a 500. Whitespace-only ids count as empty: they are not usable as document keys. """ for name, value in (('snapshot_id', snapshot_id), ('session_id', session_id)): if value is not None and not value.strip(): - raise GenkitError( - status='INVALID_ARGUMENT', - message=f'{name} must not be empty or whitespace-only.', + raise PublicError( + 'INVALID_ARGUMENT', + f'{name} must not be empty or whitespace-only.', reason=(ErrorReason.INVALID_SNAPSHOT_ID if name == 'snapshot_id' else ErrorReason.SESSION_ID_REQUIRED), ) if bool(snapshot_id) == bool(session_id): - raise GenkitError( - status='INVALID_ARGUMENT', - message=( + raise PublicError( + 'INVALID_ARGUMENT', + ( "get_snapshot requires exactly one of 'snapshot_id' or 'session_id' " f'(got snapshot_id={snapshot_id!r}, session_id={session_id!r}).' ), diff --git a/packages/genkit/src/genkit/_ai/_generate.py b/packages/genkit/src/genkit/_ai/_generate.py index eb178f0f4..34b6695e7 100644 --- a/packages/genkit/src/genkit/_ai/_generate.py +++ b/packages/genkit/src/genkit/_ai/_generate.py @@ -2740,9 +2740,9 @@ async def resolve_resume_options( last_message = messages[-1] if messages else None tool_requests = [p for p in last_message.content if p.tool_request is not None] if last_message else [] if last_message is None or last_message.role != Role.MODEL or len(tool_requests) == 0: - raise GenkitError( - status='FAILED_PRECONDITION', - message=( + raise PublicError( + 'FAILED_PRECONDITION', + ( "Cannot 'resume' generation unless the previous message is a model " 'message with at least one tool request.' ), @@ -2793,9 +2793,9 @@ async def resolve_resume_options( return (options, interrupted, None) if len(tool_responses) != len(tool_requests): - raise GenkitError( - status='FAILED_PRECONDITION', - message=f'Expected {len(tool_requests)} responses, but resolved to {len(tool_responses)}', + raise PublicError( + 'FAILED_PRECONDITION', + f'Expected {len(tool_requests)} responses, but resolved to {len(tool_responses)}', reason=ErrorReason.INVALID_RESUME, ) @@ -2942,9 +2942,9 @@ async def resolve_resumed_tool( executed, ) - raise GenkitError( - status='INVALID_ARGUMENT', - message=f"Unresolved tool request '{tool_req.name}' " + raise PublicError( + 'INVALID_ARGUMENT', + f"Unresolved tool request '{tool_req.name}' " + "was not handled by the 'resume' argument. You must supply replies or " + 'restarts for all interrupted tool requests.', reason=ErrorReason.UNRESOLVED_TOOL_REQUEST, diff --git a/packages/genkit/src/genkit/_core/_error.py b/packages/genkit/src/genkit/_core/_error.py index 4c55b2636..5777244db 100644 --- a/packages/genkit/src/genkit/_core/_error.py +++ b/packages/genkit/src/genkit/_core/_error.py @@ -739,15 +739,24 @@ class PublicError(GenkitError): other GenkitError is 500 Internal Error on the wire. """ - def __init__(self, status: StatusName, message: str, details: Any = None) -> None: # noqa: ANN401 + def __init__( + self, + status: StatusName, + message: str, + details: Any = None, # noqa: ANN401 + *, + reason: ErrorReason | None = None, + ) -> None: """Initialize a PublicError. Args: status: The status name for this error. message: The error message. details: Optional details to include. + reason: Extra why when the failure has a stable classification; + stored on ``details['reason']``. """ - super().__init__(status=status, message=message, details=details) + super().__init__(status=status, message=message, details=details, reason=reason) _INTERNAL_CLIENT_BODY: dict[str, Any] = {'message': 'Internal Error', 'status': 'INTERNAL'} diff --git a/packages/genkit/tests/genkit/core/error_test.py b/packages/genkit/tests/genkit/core/error_test.py index 0e2f7be2c..80d51a86e 100644 --- a/packages/genkit/tests/genkit/core/error_test.py +++ b/packages/genkit/tests/genkit/core/error_test.py @@ -264,6 +264,28 @@ def test_public_error() -> None: assert error.message == 'Please log in' assert error.details['extra_msg'] == 'Session expired' + classified = PublicError( + 'NOT_FOUND', + "Snapshot 'snap-1' not found", + reason=ErrorReason.SNAPSHOT_NOT_FOUND, + ) + assert classified.reason is ErrorReason.SNAPSHOT_NOT_FOUND + assert classified.details == {'reason': 'SNAPSHOT_NOT_FOUND'} + assert error_body(classified) == { + 'status': 'NOT_FOUND', + 'message': "Snapshot 'snap-1' not found", + 'details': {'reason': 'SNAPSHOT_NOT_FOUND'}, + } + + merged = PublicError( + 'INVALID_ARGUMENT', + 'Bad request', + details={'field': 'snapshotId'}, + reason=ErrorReason.INVALID_INPUT, + ) + assert merged.reason is ErrorReason.INVALID_INPUT + assert merged.details == {'field': 'snapshotId', 'reason': 'INVALID_INPUT'} + def test_genkit_error_message_is_the_sentence_they_passed() -> None: """err.message is the text passed as message=, without the status prefix.""" diff --git a/packages/genkit/tests/typecheck/init_kwonly_contract_test.py b/packages/genkit/tests/typecheck/init_kwonly_contract_test.py index 323f428dd..510227b6c 100644 --- a/packages/genkit/tests/typecheck/init_kwonly_contract_test.py +++ b/packages/genkit/tests/typecheck/init_kwonly_contract_test.py @@ -28,7 +28,7 @@ import pytest -from genkit import FlowContext, Genkit, Prompt, ToolContext +from genkit import ErrorReason, FlowContext, Genkit, Prompt, PublicError, ToolContext from genkit._core._action import ActionRunContext, BidiAction from genkit.exp.agent import AgentContext from genkit.middleware import MiddlewareContext @@ -93,12 +93,18 @@ def test_keyword_only_constructors_accept_documented_shapes() -> None: context={'table': 4}, telemetry_labels={'service': 'dining'}, ) + pub_err = PublicError( + 'NOT_FOUND', + "Snapshot 'snap-1' not found", + reason=ErrorReason.SNAPSHOT_NOT_FOUND, + ) assert run_ctx.context == {'table': 4} assert model_ctx.context == {'table': 4} assert agent_ctx.context == {'table': 4} assert tool_ctx.is_resumed() is True assert mw_ctx.telemetry_labels == {'service': 'dining'} + assert pub_err.reason is ErrorReason.SNAPSHOT_NOT_FOUND def test_positional_arguments_past_star_fail_type_checkers_and_runtime() -> None: @@ -133,6 +139,9 @@ def test_positional_arguments_past_star_fail_type_checkers_and_runtime() -> None with pytest.raises(TypeError, match='positional argument'): MiddlewareContext(ai, {'table': 4}) # pyright: ignore[reportCallIssue] # pyrefly: ignore[bad-argument-count] # ty: ignore[too-many-positional-arguments] + with pytest.raises(TypeError, match='positional argument'): + PublicError('NOT_FOUND', 'missing', None, ErrorReason.SNAPSHOT_NOT_FOUND) # pyright: ignore[reportCallIssue] # pyrefly: ignore[bad-argument-count] # ty: ignore[too-many-positional-arguments] + @pytest.mark.parametrize( ('cls', 'positional_names'), @@ -143,6 +152,7 @@ def test_positional_arguments_past_star_fail_type_checkers_and_runtime() -> None (ActionRunContext, ['self']), (ToolContext, ['self', 'ctx']), (MiddlewareContext, ['self', 'ai']), + (PublicError, ['self', 'status', 'message', 'details']), ], ) def test_every_non_identity_init_param_is_keyword_only( From d1d4701a34ad7915c24789877299867e0bc5e55a Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Wed, 11 Nov 2026 22:44:04 -0600 Subject: [PATCH 8/8] fix(py/web): serve unredacted error text under GENKIT_ENV=dev, matching Go Go's wire.ClientMessage returns err.Error() when GENKIT_ENV=dev, for both a served agent's failed turn (clientSafeError) and a served flow (clientError). client_safe_failure and error_body now do the same. Status and HTTP code are unchanged, so error_status still pairs with error_body. --- .../genkit/src/genkit/_ai/_agents/_runtime.py | 4 +-- packages/genkit/src/genkit/_core/_error.py | 22 ++++++++++++--- packages/genkit/src/genkit/web/__init__.py | 2 ++ .../genkit/tests/genkit/core/error_test.py | 16 +++++++++++ packages/genkit/tests/genkit/core/web_test.py | 27 +++++++++++++++++++ 5 files changed, 65 insertions(+), 6 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_agents/_runtime.py b/packages/genkit/src/genkit/_ai/_agents/_runtime.py index 66e01559c..3482c2ea2 100644 --- a/packages/genkit/src/genkit/_ai/_agents/_runtime.py +++ b/packages/genkit/src/genkit/_ai/_agents/_runtime.py @@ -1203,8 +1203,8 @@ def to_error_details(exc: BaseException, *, agent: str | None = None) -> Failure The Failure keeps the exception's own text, like JS ``toErrorDetails`` and Go ``convertKeepText``, so in-process callers, the session store and the Dev UI see what went wrong. A served agent's HTTP caller doesn't: - ``genkit.web`` swaps in a generic message unless the turn raised a - ``PublicError`` (see ``client_safe_failure``). Every non-``PublicError`` + outside ``GENKIT_ENV=dev``, ``genkit.web`` swaps in a generic message + unless the turn raised a ``PublicError`` (see ``client_safe_failure``). Every non-``PublicError`` failure (except an escaped ``Interrupt``) is logged here unless ``generate`` already logged it, so the server log has what the wire redacts. diff --git a/packages/genkit/src/genkit/_core/_error.py b/packages/genkit/src/genkit/_core/_error.py index 5777244db..3d56d5627 100644 --- a/packages/genkit/src/genkit/_core/_error.py +++ b/packages/genkit/src/genkit/_core/_error.py @@ -35,6 +35,7 @@ from typing_extensions import Self from genkit._core._compat import StrEnum +from genkit._core._environment import is_dev_environment from genkit._core._typing import _RuntimeErrorWire @@ -223,10 +224,9 @@ def client_safe_failure(failure: Failure) -> Failure: and cleaned details go out as is. Anything else keeps its status, since callers branch on it, but gets a generic message for that status and no details, so exception text, provider responses and internal ids stay in - the process, the store and the server log. Mirrors Go's - ``clientSafeError``, except ``GENKIT_ENV=dev`` still redacts here - (matching ``error_body``; the Dev UI reads unredacted errors over - reflection). + the process, the store and the server log. Under ``GENKIT_ENV=dev`` the + failure goes out unredacted, so a local curl shows the real cause. Mirrors + Go's ``clientSafeError`` / ``wire.ClientMessage``. """ if failure._public: details = _client_details(failure.details) @@ -239,6 +239,8 @@ def client_safe_failure(failure: Failure) -> Failure: details=details if isinstance(details, dict) else None, ) ) + if is_dev_environment(): + return failure status = failure.status message = 'Internal Error' if status is None or status == 'INTERNAL' else status.replace('_', ' ').title() return Failure(status=status, message=message) @@ -777,6 +779,13 @@ def _client_facing_error(error: object) -> GenkitError | None: return None +def _dev_client_message(error: object) -> str: + """The text ``GENKIT_ENV=dev`` serves in place of ``Internal Error``, like Go's ``err.Error()``.""" + if isinstance(error, GenkitError): + return _split_rendered(error)[1] + return str(error) or type(error).__name__ + + # Pydantic's built-in messages read from the schema (expected type, length, # Literal choices). These also put the input or the server's own text in the # message: a validator's ValueError/assertion, a discriminator tag the caller @@ -965,6 +974,9 @@ def error_body(error: Exception) -> dict[str, Any]: fields without their values, such as ``"Invalid input for flow 'save': qty: Input should be a valid integer"``. Any other GenkitError, a provider error, and anything else become ``{"message": "Internal Error", "status": "INTERNAL"}``. + Under ``GENKIT_ENV=dev`` that body carries the error's own text instead, + so a local curl shows the real cause; the status stays ``INTERNAL``. + Mirrors Go's ``wire.ClientMessage``. Example: ```python @@ -978,6 +990,8 @@ def error_body(error: Exception) -> dict[str, Any]: """ facing = _client_facing_error(error) if facing is None: + if is_dev_environment(): + return {'message': _dev_client_message(error), 'status': 'INTERNAL'} return dict(_INTERNAL_CLIENT_BODY) message = facing.message if isinstance(facing, PublicError) else _request_client_message(facing) body: dict[str, Any] = { diff --git a/packages/genkit/src/genkit/web/__init__.py b/packages/genkit/src/genkit/web/__init__.py index 3fb01339b..eebe9dc22 100644 --- a/packages/genkit/src/genkit/web/__init__.py +++ b/packages/genkit/src/genkit/web/__init__.py @@ -28,6 +28,8 @@ your logs. ``result_json`` and ``to_sse`` apply the same rule to a failed agent turn's ``error`` (an ``AgentOutput`` or ``SessionSnapshot``), which goes out in a 200: it keeps its status, and a non-public message becomes generic. +Under ``GENKIT_ENV=dev`` both keep the error's own text, like Go, so a local +curl against a served flow or agent shows the real cause. A ``ContextProvider`` reads the ``RequestData`` for one request and returns what goes into the flow's context. diff --git a/packages/genkit/tests/genkit/core/error_test.py b/packages/genkit/tests/genkit/core/error_test.py index 80d51a86e..f4a5068b8 100644 --- a/packages/genkit/tests/genkit/core/error_test.py +++ b/packages/genkit/tests/genkit/core/error_test.py @@ -442,6 +442,22 @@ def test_error_status_matches_error_body_status() -> None: assert (error_status(crash), error_body(crash)['status']) == (500, 'INTERNAL') +def test_error_body_under_genkit_env_dev_keeps_text_but_not_status(monkeypatch: pytest.MonkeyPatch) -> None: + """GENKIT_ENV=dev swaps only the message, so error_status and the body's status still agree.""" + monkeypatch.setenv('GENKIT_ENV', 'dev') + unavailable = GenkitError(status='UNAVAILABLE', message='overloaded', cause=RuntimeError('503 from provider')) + public = PublicError('NOT_FOUND', 'no order 99') + + assert error_body(ValueError('secret')) == {'message': 'secret', 'status': 'INTERNAL'} + assert error_body(ValueError()) == {'message': 'ValueError', 'status': 'INTERNAL'} + assert error_body(unavailable) == {'message': 'overloaded: 503 from provider', 'status': 'INTERNAL'} + assert error_status(unavailable) == 500 + assert error_body(public) == {'message': 'no order 99', 'status': 'NOT_FOUND'} + + monkeypatch.setenv('GENKIT_ENV', 'prod') + assert error_body(ValueError('secret')) == {'message': 'Internal Error', 'status': 'INTERNAL'} + + def test_served_error_body_for_internal_wrapper_around_wrapped_raw_error_is_internal_error() -> None: """An INTERNAL wrapper around another wrapped raw raise sends neither wrapper's text.""" nested = GenkitError( diff --git a/packages/genkit/tests/genkit/core/web_test.py b/packages/genkit/tests/genkit/core/web_test.py index c1aff9617..b4a0638bd 100644 --- a/packages/genkit/tests/genkit/core/web_test.py +++ b/packages/genkit/tests/genkit/core/web_test.py @@ -31,6 +31,7 @@ # to_error_details and AgentOutput are private: this test pins the served wire shape. from genkit._ai._agents._runtime import to_error_details # noqa: TID251 from genkit._core._model import AgentOutput # noqa: TID251 +from genkit._core._typing import AgentFinishReason # noqa: TID251 from genkit.plugin_api import Action from genkit.web import error_json, error_sse, read_body, result_json, to_sse, wants_stream @@ -181,6 +182,32 @@ def test_error_json_and_error_sse_preserve_public_errors_and_redact_internal_one assert error_sse(secret) == 'data: {"error":{"message":"Internal Error","status":"INTERNAL"}}\n\n' +def test_genkit_env_dev_serves_the_real_error_text_like_go(monkeypatch: pytest.MonkeyPatch) -> None: + """Under GENKIT_ENV=dev a local curl sees the cause, like Go's wire.ClientMessage; statuses don't change.""" + # 1. Dev mode, as `genkit start` sets it + monkeypatch.setenv('GENKIT_ENV', 'dev') + + # 2. A failed agent turn keeps its own text and status + private = AgentOutput( + finish_reason=AgentFinishReason.FAILED, error=to_error_details(ValueError('db password=hunter2')) + ) + not_found = AgentOutput( + finish_reason=AgentFinishReason.FAILED, + error=to_error_details(genkit.GenkitError(status='NOT_FOUND', message='no row for order A-17')), + ) + assert result_json(private) == ( + '{"result":{"finishReason":"failed","error":{"status":"INTERNAL","message":"db password=hunter2"}}}' + ) + assert result_json(not_found) == ( + '{"result":{"finishReason":"failed","error":{"status":"NOT_FOUND","message":"no row for order A-17"}}}' + ) + + # 3. A failed flow keeps its text and cause, still a 500 INTERNAL + crash = genkit.GenkitError(status='INTERNAL', message='model call failed', cause=ValueError('quota exceeded')) + assert error_json(crash) == '{"message":"model call failed: quota exceeded","status":"INTERNAL"}' + assert error_sse(RuntimeError('pg down')) == 'data: {"error":{"message":"pg down","status":"INTERNAL"}}\n\n' + + @pytest.mark.asyncio async def test_web_encoders_emit_unescaped_utf8() -> None: """Non-ASCII UTF-8 strings serialize unescaped across JSON and SSE encoders."""