pydantic-ai/tests/durable_exec/test_capability_durable_operation.py

2784 lines
105 KiB
Python

from __future__ import annotations
import copy
import gc
import inspect
import re
import uuid
from collections.abc import AsyncGenerator, AsyncIterable, AsyncIterator, Awaitable, Callable, Generator, Mapping
from contextlib import asynccontextmanager
from dataclasses import dataclass, replace
from decimal import Decimal
from typing import TYPE_CHECKING, Any, cast
import pytest
from inline_snapshot import snapshot
from pydantic_core import PydanticSerializationError
from pydantic_ai import Agent, AgentStreamEvent, FinalResultEvent, ModelMessage, ModelSettings
from pydantic_ai.agent import AbstractAgent, AgentRunResult
from pydantic_ai.capabilities import (
CAPABILITY_TYPES,
AbstractCapability,
BatchModelRequests,
CombinedCapability,
FileUnderstanding,
Instrumentation,
ModelFallback,
ProcessEventStream,
ResolveModelId,
SelectModel,
WrapperCapability,
WrapRunHandler,
durable_operation,
)
from pydantic_ai.capabilities.abstract import AgentModel
from pydantic_ai.durable_exec import DurabilityEngineSpec
from pydantic_ai.durable_exec._base import BaseDurabilityCapability
from pydantic_ai.durable_exec._capability_operation import (
CapabilityMethodDeclaration,
CapabilityOperationParams,
CapabilityOperationResult,
ModelRequestContextProjection,
base_hook_durable_operation,
call_declaration,
collect_capability_operations,
recover_capability,
)
from pydantic_ai.durable_exec._codec import JSON_CODEC
from pydantic_ai.durable_exec._operation import CapabilityOperationId, DurableOperationId, OperationConfigRole
from pydantic_ai.durable_exec._operation_backend import CallableOperationBackend
from pydantic_ai.durable_exec._operation_names import JournalOperationNamer
from pydantic_ai.durable_exec._toolset import ToolConfig
from pydantic_ai.exceptions import ModelAPIError, ModelRetry, UserError
from pydantic_ai.messages import (
CapabilityEvent,
DocumentUrl,
ModelRequest,
ModelResponse,
TextPart,
ToolCallPart,
UserPromptPart,
)
from pydantic_ai.models import (
Model,
ModelRequestContext,
ModelRequestParameters,
ModelResolutionContext,
StreamedResponse,
)
from pydantic_ai.models._batch_model import BatchedModel
from pydantic_ai.models.function import AgentInfo, DeltaToolCall, DeltaToolCalls, FunctionModel
from pydantic_ai.models.test import TestModel
from pydantic_ai.profiles import ModelProfile
from pydantic_ai.tools import RunContext, Tool
from pydantic_ai.toolsets import FunctionToolset
from pydantic_ai.usage import RequestUsage, RunUsage
from ..batch_utils import FAST_BATCH_SETTINGS
from ..conftest import try_import
from ..model_lifecycle_utils import LifecycleTrackingModel
from .preamble_text import (
RunAndStreamResult,
StructuredOutput,
plain_run_and_stream,
preamble_text_agents,
run_and_stream,
)
with try_import() as logfire_installed:
from logfire.testing import CaptureLogfire
if TYPE_CHECKING:
from dbos import DBOS, DBOSConfig, SetWorkflowID
from prefect import flow
from temporalio.activity import _Definition as ActivityDefinition # pyright: ignore[reportPrivateUsage]
from pydantic_ai.durable_exec.dbos import DBOSDurability
from pydantic_ai.durable_exec.prefect import PrefectDurability
from pydantic_ai.durable_exec.temporal import TemporalDurability
from pydantic_ai.durable_exec.temporal._transports import _CapabilityOperationParams, _CapabilityOperationTransport
dbos_available = prefect_available = temporal_available = False
else:
try:
from dbos import DBOS, DBOSConfig, SetWorkflowID
from pydantic_ai.durable_exec.dbos import DBOSDurability
dbos_available = True
except ImportError: # pragma: lax no cover
DBOS = DBOSConfig = SetWorkflowID = DBOSDurability = cast(Any, None)
dbos_available = False
try:
from prefect import flow
from pydantic_ai.durable_exec.prefect import PrefectDurability
prefect_available = True
except ImportError: # pragma: lax no cover
flow = PrefectDurability = cast(Any, None)
prefect_available = False
try:
from temporalio.activity import _Definition as ActivityDefinition # pyright: ignore[reportPrivateUsage]
from pydantic_ai.durable_exec.temporal import TemporalDurability
from pydantic_ai.durable_exec.temporal._transports import ( # pyright: ignore[reportPrivateUsage]
_CapabilityOperationParams,
_CapabilityOperationTransport,
)
temporal_available = True
except ImportError: # pragma: lax no cover
ActivityDefinition = TemporalDurability = cast(Any, None)
temporal_available = False
requires_dbos = pytest.mark.skipif(not dbos_available, reason='DBOS is not installed')
requires_prefect = pytest.mark.skipif(not prefect_available, reason='Prefect is not installed')
requires_temporal = pytest.mark.skipif(not temporal_available, reason='Temporal is not installed')
@pytest.fixture(autouse=True)
def blockbuster_enabled() -> bool:
return False
class _RecordingConfig:
def base(self, role: OperationConfigRole, operation_id: DurableOperationId) -> ToolConfig:
return {}
def for_tool(
self, role: OperationConfigRole, operation_id: DurableOperationId, tool: object | None, tool_name: str
) -> ToolConfig:
return {}
class _RecordingBackend(CallableOperationBackend[ToolConfig]):
def __init__(self, durability: RecordingDurability) -> None:
super().__init__(namer=JournalOperationNamer(durability.name), config=_RecordingConfig())
self._durability = durability
async def execute(
self,
*,
operation_id: DurableOperationId,
name: str,
body: Callable[[], Awaitable[object]],
cache_key: tuple[object, ...],
config: object,
) -> object:
durability = self._durability
durability.calls.append((name, cache_key))
if not durability.replay_capability_operations or '__capability__' not in name:
return await body()
if name not in durability.recorded_results:
durability.recorded_results[name] = await body()
return durability.recorded_results[name]
class RecordingDurability(BaseDurabilityCapability[Any]):
engine_spec = DurabilityEngineSpec(
engine_name='recording',
durable_unit_noun='unit',
durable_container_noun='journal',
codec=JSON_CODEC,
)
replay_capability_operations = False
def __init__(self, *, models: Mapping[str, Model] | None = None) -> None:
super().__init__(models=models)
self.calls: list[tuple[str, tuple[object, ...]]] = []
self.recorded_results: dict[str, Any] = {}
@property
def in_durable_context(self) -> bool:
return True
def get_durable_operation_backend(self) -> CallableOperationBackend[ToolConfig]:
return _RecordingBackend(self)
class ReplayingDurability(RecordingDurability):
replay_capability_operations = True
class TransparentDurability(RecordingDurability):
@property
def in_durable_context(self) -> bool:
return False
class ModelIdReplacingBeforeModelRequest(AbstractCapability[Any]):
id = 'model_id_replacing_before_model'
@durable_operation('before_model_request')
async def before_model_request(
self, ctx: RunContext[Any], request_context: ModelRequestContext
) -> ModelRequestContext:
request_context.model_id = 'tracked'
return request_context
class LifecycleModel(LifecycleTrackingModel):
def __init__(self, events: list[str], **kwargs: Any) -> None:
super().__init__(events, event_prefix='model-', **kwargs)
@asynccontextmanager
async def request_stream(
self,
messages: list[ModelMessage],
model_settings: ModelSettings | None,
model_request_parameters: ModelRequestParameters,
run_context: RunContext[Any] | None = None,
) -> AsyncGenerator[StreamedResponse]:
self.events.append('stream-enter')
try:
async with super().request_stream(
messages, model_settings, model_request_parameters, run_context
) as streamed:
yield streamed
finally:
self.events.append('stream-exit')
class RepeatingLifecycleModel(LifecycleTrackingModel):
async def request(
self,
messages: list[ModelMessage],
model_settings: ModelSettings | None,
model_request_parameters: ModelRequestParameters,
) -> ModelResponse:
self.events.append('request')
return ModelResponse(parts=[TextPart('from-tracked')])
def _tracked_model_resolver(
built: list[LifecycleTrackingModel],
*,
events: list[str] | None = None,
event_prefix: str = '',
model_type: type[LifecycleTrackingModel] = LifecycleTrackingModel,
) -> Callable[[ModelResolutionContext[Any], str], LifecycleTrackingModel]:
"""Build a fresh model for the one id these tests swap to, recording every instance.
Shared across the tests below rather than repeated inside each: the outside-a-container test
asserts this is never consulted, so a resolver of its own would leave a body nothing executes.
Each call gets its own event list unless the caller supplies one to share.
"""
def resolve(_ctx: ModelResolutionContext[Any], model_id: str) -> LifecycleTrackingModel:
del model_id
model = model_type(
events if events is not None else [],
event_prefix=event_prefix,
custom_output_text='from-tracked',
)
built.append(model)
return model
return resolve
class _BindLoggingDurability(RecordingDurability):
"""Logs each bind, which is where an engine registers its durable operations."""
def __init__(self, bound: list[str]) -> None:
super().__init__()
self._bound = bound
def _bind_for_agent(self, agent: AbstractAgent[Any, Any]) -> _BindLoggingDurability:
self._bound.append(self.engine_name)
return super()._bind_for_agent(agent)
class _OtherEngineDurability(_BindLoggingDurability):
engine_spec = DurabilityEngineSpec(
engine_name='other',
durable_unit_noun='unit',
durable_container_noun='journal',
codec=JSON_CODEC,
)
_SECOND_ENGINE = re.escape(
'An agent can have only one durable execution engine, but this one would have 2: '
'`_BindLoggingDurability`, `_OtherEngineDurability`.'
)
def test_a_second_durable_engine_is_refused_at_construction() -> None:
bound: list[str] = []
with pytest.raises(UserError, match=_SECOND_ENGINE):
Agent(
TestModel(),
name='two_engines',
capabilities=[_BindLoggingDurability(bound), _OtherEngineDurability(bound)],
)
assert bound == []
@pytest.mark.parametrize('wrap', [False, True], ids=['bare', 'wrapped'])
def test_a_durable_engine_inside_a_capability_group_is_refused(wrap: bool) -> None:
"""A deferred group can't hold the engine that has to wrap every toolset the agent has."""
bound: list[str] = []
engine: AbstractCapability[Any] = _BindLoggingDurability(bound)
with pytest.raises(UserError) as exc_info:
Agent(
TestModel(),
name='grouped_engine',
capabilities=[
CombinedCapability(
[WrapperCapability(engine) if wrap else engine],
id='infra',
description='Infra.',
defer_loading=True,
)
],
)
assert str(exc_info.value) == snapshot(
"`_BindLoggingDurability` is inside capability 'infra', but a durable execution engine must be passed to "
'the agent directly, so it can wrap every toolset the agent has.'
)
assert bound == []
async def test_two_durable_engines_for_one_run_are_refused_before_either_binds() -> None:
bound: list[str] = []
agent = Agent(TestModel(), name='two_engines')
with pytest.raises(UserError, match=_SECOND_ENGINE):
await agent.run('hi', capabilities=[_BindLoggingDurability(bound), _OtherEngineDurability(bound)])
assert bound == []
async def test_a_durable_engine_for_a_run_is_refused_beside_the_agents_own() -> None:
bound: list[str] = []
agent = Agent(TestModel(), name='two_engines', capabilities=[_BindLoggingDurability(bound)])
assert bound == ['recording']
with pytest.raises(UserError, match=_SECOND_ENGINE):
await agent.run('hi', capabilities=[_OtherEngineDurability(bound)])
assert bound == ['recording'], 'the run-level engine never bound'
async def test_a_durable_engine_returned_by_a_capability_factory_is_refused() -> None:
"""A factory's capability only exists once `for_run` resolves it, after the pre-bind check."""
bound: list[str] = []
agent = Agent(TestModel(), name='factory_engine', capabilities=[_BindLoggingDurability(bound)])
other = _OtherEngineDurability(bound)
with pytest.raises(UserError, match=_SECOND_ENGINE):
await agent.run('hi', capabilities=[lambda ctx: other])
assert other.calls == [], 'the factory engine never took over dispatch'
def test_two_durable_engines_in_an_override_spec_are_refused(monkeypatch: pytest.MonkeyPatch) -> None:
"""`override(spec=...)` replaces the agent's capabilities with the spec's, and binds them itself."""
bound: list[str] = []
class _SpecEngine(_BindLoggingDurability):
def __init__(self) -> None:
super().__init__(bound)
@classmethod
def get_serialization_name(cls) -> str:
return 'SpecEngine'
class _OtherSpecEngine(_OtherEngineDurability):
def __init__(self) -> None:
super().__init__(bound)
@classmethod
def get_serialization_name(cls) -> str:
return 'OtherSpecEngine'
monkeypatch.setitem(CAPABILITY_TYPES, 'SpecEngine', _SpecEngine)
monkeypatch.setitem(CAPABILITY_TYPES, 'OtherSpecEngine', _OtherSpecEngine)
agent = Agent(TestModel(), name='override_two_engines')
with pytest.raises(UserError, match='would have 2: `_SpecEngine`, `_OtherSpecEngine`'):
with agent.override(spec={'capabilities': ['SpecEngine', 'OtherSpecEngine']}):
pass # pragma: no cover
assert bound == []
async def test_one_durable_engine_listed_twice_is_refused() -> None:
engine = _BindLoggingDurability([])
agent = Agent(TestModel(), name='one_engine_twice')
with pytest.raises(UserError, match='would have 2: `_BindLoggingDurability`, `_BindLoggingDurability`'):
await agent.run('hi', capabilities=[engine, engine])
def test_a_wrapped_durable_engine_still_counts() -> None:
bound: list[str] = []
with pytest.raises(UserError, match=_SECOND_ENGINE):
Agent(
TestModel(),
name='wrapped_engine',
capabilities=[_BindLoggingDurability(bound).prefix_tools('p'), _OtherEngineDurability(bound)],
)
async def test_capability_operation_is_direct_outside_durable_context() -> None:
events: list[str] = []
built_models: list[LifecycleTrackingModel] = []
resolve_model = _tracked_model_resolver(built_models, events=events, event_prefix='tracked-')
durability = TransparentDurability()
agent = Agent(
TestModel(custom_output_text='original'),
name='direct_capability_operation',
capabilities=[ModelIdReplacingBeforeModelRequest(), ResolveModelId(resolve_model), durability],
)
assert (await agent.run('test')).output == 'original'
assert events == []
assert built_models == []
assert not any('__capability__' in name for name, _ in durability.calls)
async def test_capability_operation_maps_serialization_failure() -> None:
"""The engine's backend receives the error that `serialization_failure` maps an unserializable result to."""
class TerminalFailure(Exception):
pass
backend_errors: list[Exception] = []
def serialization_failure(exc: Exception) -> TerminalFailure:
return TerminalFailure()
class SerializationBackend(_RecordingBackend):
async def execute(
self,
*,
operation_id: DurableOperationId,
name: str,
body: Callable[[], Awaitable[object]],
cache_key: tuple[object, ...],
config: object,
) -> object:
try:
return await super().execute(
operation_id=operation_id, name=name, body=body, cache_key=cache_key, config=config
)
except Exception as exc:
backend_errors.append(exc)
raise
class SerializationDurability(RecordingDurability):
engine_spec = replace(RecordingDurability.engine_spec, serialization_failure=serialization_failure)
def get_durable_operation_backend(self) -> SerializationBackend:
return SerializationBackend(self)
class NonSerializableCapability(AbstractCapability[None]):
id = 'non_serializable'
async def before_run(self, ctx: RunContext[None]) -> None:
await self.read(ctx=ctx)
@durable_operation('read')
async def read(self, ctx: RunContext[None]) -> object:
return object()
agent = Agent(
TestModel(),
deps_type=type(None),
name='serialization_failure',
capabilities=[NonSerializableCapability(), SerializationDurability()],
)
with pytest.raises(TerminalFailure) as exc_info:
await agent.run('test')
assert backend_errors == [exc_info.value]
assert isinstance(exc_info.value.__cause__, PydanticSerializationError)
async def test_capability_operation_model_id_swap_resolves_and_manages_model() -> None:
events: list[str] = []
built_models: list[LifecycleTrackingModel] = []
resolve_model = _tracked_model_resolver(built_models, events=events, event_prefix='tracked-')
durability = RecordingDurability()
agent = Agent(
TestModel(custom_output_text='original'),
name='durable_capability_operation',
capabilities=[ModelIdReplacingBeforeModelRequest(), ResolveModelId(resolve_model), durability],
)
assert (await agent.run('test')).output == 'from-tracked'
assert events == [
'tracked-enter',
'tracked-enter',
'request',
'tracked-exit:none',
'tracked-exit:none',
]
assert len(built_models) == 2
assert any('__capability__' in name for name, _ in durability.calls)
async def test_capability_operation_registered_model_id_swap_does_not_manage_model() -> None:
events: list[str] = []
registered = LifecycleTrackingModel(events, event_prefix='registered-', custom_output_text='from-registered')
durability = RecordingDurability(models={'tracked': registered})
agent = Agent(
TestModel(custom_output_text='original'),
name='registered_capability_operation_model',
capabilities=[ModelIdReplacingBeforeModelRequest(), durability],
)
assert (await agent.run('test')).output == 'from-registered'
assert events == ['request']
async def test_fallback_attempts_dispatch_through_durable_operations() -> None:
"""Each attempt `ModelFallback` moves to runs as a durable model operation, never inline in workflow code."""
def failing(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
raise ModelAPIError(model_name='failing', message='boom')
durability = RecordingDurability(models={'registered': TestModel(custom_output_text='from-fallback')})
agent = Agent(
FunctionModel(failing),
name='fallback_durable',
capabilities=[ModelFallback('registered'), durability],
)
assert (await agent.run('test')).output == 'from-fallback'
assert [name for name, _ in durability.calls if '__model.' in name] == snapshot(
['fallback_durable__model.request', 'fallback_durable__model.request.registered']
)
async def test_model_fallback_supplies_the_model_of_a_durable_agent_without_one() -> None:
"""An agent with no model of its own can be made durable when `ModelFallback` supplies its first candidate."""
def failing(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
raise ModelAPIError(model_name='failing', message='boom')
models: dict[str, Model] = {
'primary': FunctionModel(failing),
'secondary': TestModel(custom_output_text='from-secondary'),
}
durability = RecordingDurability(models=models)
agent = Agent(name='model_less_durable', capabilities=[ModelFallback('primary', 'secondary'), durability])
assert (await agent.run('test')).output == 'from-secondary'
assert [name for name, _ in durability.calls if '__model.' in name] == snapshot(
['model_less_durable__model.request.primary', 'model_less_durable__model.request.secondary']
)
@dataclass
class _SuppliesRegisteredModel(AbstractCapability[Any]):
"""A capability of the user's own that supplies the agent's model."""
def get_model(self) -> AgentModel[Any] | None:
return 'registered'
@pytest.mark.parametrize(
'supplier',
[
pytest.param(lambda: SelectModel(lambda ctx: 'registered'), id='select_model'),
pytest.param(_SuppliesRegisteredModel, id='custom_get_model'),
pytest.param(lambda: WrapperCapability(wrapped=SelectModel(lambda ctx: 'registered')), id='wrapped'),
],
)
async def test_a_capability_supplies_the_model_of_a_durable_agent_without_one(
supplier: Callable[[], AbstractCapability[Any]],
) -> None:
durability = RecordingDurability(models={'registered': TestModel(custom_output_text='from-registered')})
agent = Agent(name='capability_model_durable', capabilities=[supplier(), durability])
assert (await agent.run('test')).output == 'from-registered'
assert [name for name, _ in durability.calls if '__model.' in name] == [
'capability_model_durable__model.request.registered'
]
def test_a_durable_agent_without_a_model_or_a_capability_that_supplies_one_is_rejected() -> None:
with pytest.raises(UserError, match='needs to have a `model` in order to be used with recording'):
Agent(name='model_less', capabilities=[RecordingDurability()])
async def test_resolved_request_model_records_are_released_with_their_models() -> None:
built_models: list[LifecycleTrackingModel] = []
durability = RecordingDurability()
agent = Agent(
TestModel(custom_output_text='original'),
name='released_capability_operation_model',
capabilities=[
ModelIdReplacingBeforeModelRequest(),
ResolveModelId(_tracked_model_resolver(built_models)),
durability,
],
)
await agent.run('test')
bound = RecordingDurability.from_agent(agent)
assert bound is not None
records = bound._resolved_request_models # pyright: ignore[reportPrivateUsage]
assert records
# The record outlives the request it was made for, so it has to be released with its model
# rather than accumulating one entry per swapped request for the life of the agent.
built_models.clear()
gc.collect()
assert records == {}
async def test_repeated_capability_operation_model_id_swaps_close_each_model() -> None:
built_models: list[LifecycleTrackingModel] = []
resolve_model = _tracked_model_resolver(built_models, model_type=RepeatingLifecycleModel)
agent = Agent(
TestModel(custom_output_text='original'),
name='repeated_capability_operation_model',
capabilities=[ModelIdReplacingBeforeModelRequest(), ResolveModelId(resolve_model), RecordingDurability()],
)
attempts = 0
@agent.output_validator
def retry_once(output: str) -> str:
nonlocal attempts
attempts += 1
if attempts == 1:
raise ModelRetry('retry once')
return output
assert (await agent.run('test')).output == 'from-tracked'
assert [model.events for model in built_models] == [
['enter', 'exit:none'],
['enter', 'request', 'exit:none'],
['enter', 'exit:none'],
['enter', 'request', 'exit:none'],
]
@pytest.mark.parametrize(
('stream', 'fail', 'expected_events'),
[
(False, False, ['model-enter', 'request', 'model-exit:none']),
(True, False, ['model-enter', 'stream-enter', 'stream-exit', 'model-exit:none']),
(False, True, ['model-enter', 'request', 'model-exit:RuntimeError']),
],
)
async def test_durable_model_scope_manages_rebuilt_model_lifecycle(
stream: bool, fail: bool, expected_events: list[str]
) -> None:
"""A worker-built model stays entered for its whole operation and exits on failure."""
events: list[str] = []
def resolve_model(_ctx: ModelResolutionContext[Any], _model_id: str) -> LifecycleModel:
return LifecycleModel(events, fail=fail)
agent = Agent(
'lifecycle',
name=f'rebuilt_model_lifecycle_{stream}_{fail}',
capabilities=[ResolveModelId(resolve_model), RecordingDurability()],
)
if fail:
with pytest.raises(RuntimeError, match='request failed'):
await agent.run('test')
elif stream:
async with agent.run_stream('test') as result:
assert await result.get_output() == 'ok'
else:
assert (await agent.run('test')).output == 'ok'
assert events == expected_events
async def test_durable_model_scope_does_not_suppress_body_error() -> None:
events: list[str] = []
model = LifecycleModel(events, fail=True, suppress_exit=True)
agent = Agent(
'lifecycle',
name='rebuilt_model_suppressed_exit',
capabilities=[ResolveModelId(lambda ctx, model_id: model), RecordingDurability()],
)
with pytest.raises(RuntimeError, match='request failed'):
await agent.run('test')
assert events == ['model-enter', 'request', 'model-exit:RuntimeError']
async def test_durable_model_scope_surfaces_teardown_error() -> None:
events: list[str] = []
model = LifecycleModel(events, fail=True, fail_exit=True)
agent = Agent(
'lifecycle',
name='rebuilt_model_failed_exit',
capabilities=[ResolveModelId(lambda ctx, model_id: model), RecordingDurability()],
)
with pytest.raises(ValueError, match='exit failed'):
await agent.run('test')
assert events == ['model-enter', 'request', 'model-exit:RuntimeError']
async def test_durable_model_scope_does_not_manage_registered_models() -> None:
"""The agent owner remains responsible for default and `models=` instances."""
default_events: list[str] = []
registered_events: list[str] = []
default = LifecycleModel(default_events, model_name='default')
registered = LifecycleModel(registered_events, model_name='registered')
agent = Agent(
default,
name='registered_model_lifecycle',
capabilities=[RecordingDurability(models={'registered': registered})],
)
assert (await agent.run('test')).output == 'ok'
assert (await agent.run('test', model='registered')).output == 'ok'
async with agent.run_stream('test', model='registered') as result:
assert await result.get_output() == 'ok'
assert default_events == ['request']
assert registered_events == ['request', 'stream-enter', 'stream-exit']
async def test_durable_stream_replay_classifies_parts_as_the_unit_prepared_them() -> None:
"""Text streamed before a tool call isn't the final result under any engine built on the base capability.
`DurableModel.request_stream` replays the unit's response against the parameters the unit's model prepared, in
which `'auto'` has resolved to tool output, so the replay finds the same final result as a plain run, and both
run methods replay the response's parts as the model streamed them.
"""
durable = [await run_and_stream(agent) for agent in preamble_text_agents(RecordingDurability)]
assert durable == await plain_run_and_stream()
assert durable == snapshot(
[
RunAndStreamResult(
run_output='Paris',
stream_output='Paris',
final_result_tool_names=['final_result'],
run_responses=[
[
TextPart(content='Let me look that up.'),
ToolCallPart(tool_name='look_up_city', args='{}', tool_call_id='call_1'),
],
[ToolCallPart(tool_name='final_result', args='{"response":"Paris"}', tool_call_id='call_2')],
],
stream_responses=[
[
TextPart(content='Let me look that up.'),
ToolCallPart(tool_name='look_up_city', args='{}', tool_call_id='call_1'),
],
[ToolCallPart(tool_name='final_result', args='{"response":"Paris"}', tool_call_id='call_2')],
],
),
RunAndStreamResult(
run_output='Paris',
stream_output='Paris',
final_result_tool_names=['final_result'],
run_responses=[
[
TextPart(content='Preamble text.'),
ToolCallPart(tool_name='final_result', args='{"response":"Paris"}', tool_call_id='call_2'),
]
],
stream_responses=[
[
TextPart(content='Preamble text.'),
ToolCallPart(tool_name='final_result', args='{"response":"Paris"}', tool_call_id='call_2'),
]
],
),
]
)
async def _preamble_text_before_output_tool_then_failure(
_messages: list[ModelMessage], _info: AgentInfo
) -> AsyncIterator[str | DeltaToolCalls]:
yield 'Preamble text.'
yield {0: DeltaToolCall(name='final_result', json_args='{"response":"Paris"}', tool_call_id='call_1')}
raise ModelAPIError('function', 'stream broke')
async def test_durable_stream_replay_classifies_a_failed_stream_as_the_unit_prepared_it() -> None:
"""A stream that fails after text and a tool call replays them as the unit's model classified them, then raises.
The unit hands back what the stream produced before it failed, and the replay classifies those parts against the
parameters the unit's model prepared, so the run sees the same final result before the error as a plain run.
"""
async def final_result_tool_names_until_failure(agent: Agent[object, StructuredOutput]) -> list[str | None]:
tool_names: list[str | None] = []
async def handler(ctx: RunContext[object], stream: AsyncIterable[AgentStreamEvent]) -> None:
async for event in stream:
if isinstance(event, FinalResultEvent):
tool_names.append(event.tool_name)
with pytest.raises(ModelAPIError, match='stream broke'):
await agent.run('hello', event_stream_handler=handler)
return tool_names
def agent(capabilities: list[AbstractCapability[object]]) -> Agent[object, StructuredOutput]:
return Agent(
FunctionModel(stream_function=_preamble_text_before_output_tool_then_failure),
name='durability_preamble_text_then_failure',
output_type=StructuredOutput,
capabilities=capabilities,
)
durable = await final_result_tool_names_until_failure(agent([RecordingDurability()]))
assert durable == await final_result_tool_names_until_failure(agent([]))
assert durable == snapshot(['final_result'])
async def test_durable_model_scope_manages_inferred_models(monkeypatch: pytest.MonkeyPatch) -> None:
"""A model inferred inside the worker has the same owned lifecycle as a resolver-built model."""
events: list[str] = []
def infer_lifecycle_model(_model_id: str) -> LifecycleModel:
return LifecycleModel(events)
monkeypatch.setattr('pydantic_ai.durable_exec._base.infer_model', infer_lifecycle_model)
agent = Agent('test', name='inferred_model_lifecycle', capabilities=[RecordingDurability()])
assert (await agent.run('test')).output == 'ok'
assert events == ['model-enter', 'request', 'model-exit:none']
class Operations(AbstractCapability[Any]):
id = 'operations'
def __init__(self) -> None:
self.calls: list[tuple[RunContext[Any], object]] = []
self.result: int | None = None
self.arguments: tuple[tuple[Any, ...], dict[str, Any]] = ((), {})
async def before_run(self, ctx: RunContext[Any]) -> None:
self.result = await self._calculate(ctx, *self.arguments[0], **self.arguments[1])
@durable_operation('calculate')
async def _calculate(
self,
ctx: RunContext[Any],
value: int = 2,
*extra: int,
scale: int = 1,
**offsets: int,
) -> int:
marker = object()
self.calls.append((ctx, marker))
return (value + sum(extra) + sum(offsets.values())) * scale
class DurableBeforeModelRequest(AbstractCapability[Any]):
id = 'before_model'
@durable_operation('before_model_request')
async def before_model_request(
self, ctx: RunContext[Any], request_context: ModelRequestContext
) -> ModelRequestContext:
request_context.messages = [ModelRequest(parts=[UserPromptPart('replaced')])]
return request_context
class CustomModelRequestOperation(AbstractCapability[Any]):
id = 'custom_model_request'
async def before_model_request(
self, ctx: RunContext[Any], request_context: ModelRequestContext
) -> ModelRequestContext:
return await self.rewrite_request(ctx, request_context)
@durable_operation('rewrite_request')
async def rewrite_request(self, ctx: RunContext[Any], request: ModelRequestContext) -> ModelRequestContext:
request.messages = [ModelRequest(parts=[UserPromptPart('custom replacement')])]
return request
class ModelReplacingBeforeModelRequest(AbstractCapability[Any]):
id = 'model_replacing_before_model'
def __init__(self, model: TestModel, *, model_id: str | None = None) -> None:
self.model = model
self.model_id = model_id
@durable_operation('before_model_request')
async def before_model_request(
self, ctx: RunContext[Any], request_context: ModelRequestContext
) -> ModelRequestContext:
request_context.model = self.model
request_context.model_id = self.model_id
return request_context
class RenamedContextBeforeModelRequest(AbstractCapability[Any]):
id = 'renamed_before_model'
# Only the declared context parameter name is inspected; dispatch would duplicate other hook tests.
@durable_operation('before_model_request')
async def before_model_request( # pyright: ignore[reportIncompatibleMethodOverride] # pragma: no cover
self, run_context: RunContext[Any], request_context: ModelRequestContext
) -> ModelRequestContext: ...
class ContextPositions(AbstractCapability[Any]):
id = 'context_positions'
def __init__(self) -> None:
self.results: list[str] = []
async def before_run(self, ctx: RunContext[Any]) -> None:
self.results = [
await self.ctx_first(ctx, 'first'),
await self.ctx_last('last', ctx),
await self.ctx_keyword_only('keyword', ctx=ctx),
await self.no_ctx('none'),
await self._summarize(['one', 'two'], ctx, previous_summary='previous'),
]
@durable_operation('ctx_first')
async def ctx_first(self, ctx: RunContext[Any], value: str) -> str:
return f'{value}:{ctx.model.model_name}'
@durable_operation('ctx_last')
async def ctx_last(self, value: str, ctx: RunContext[Any]) -> str:
return f'{value}:{ctx.model.model_name}'
@durable_operation('ctx_keyword_only')
async def ctx_keyword_only(self, value: str, *, ctx: RunContext[Any]) -> str:
return f'{value}:{ctx.model.model_name}'
@durable_operation('no_ctx')
async def no_ctx(self, value: str) -> str:
return value
@durable_operation('summarize')
async def _summarize(
self, messages: list[str], ctx: RunContext[Any], *, previous_summary: str | None = None
) -> str:
return f'{previous_summary}:{len(messages)}:{ctx.model.model_name}'
class PerRunOperation(AbstractCapability[Any]):
id = 'per_run_operation'
def __init__(self, replacements: list[PerRunOperation]) -> None:
self.replacements = replacements
self.calls = 0
async def for_run(self, ctx: RunContext[Any]) -> AbstractCapability[Any]:
replacement = PerRunOperation(self.replacements)
self.replacements.append(replacement)
return replacement
async def before_run(self, ctx: RunContext[Any]) -> None:
await self.operation(ctx)
@durable_operation('operation')
async def operation(self, ctx: RunContext[Any]) -> None:
self.calls += 1
class PerRequestOperation(AbstractCapability[Any]):
"""A per-run replacement whose operation takes an explicit `RunContext` and runs per request."""
id = 'per_request_operation'
def __init__(self, steps: list[int]) -> None:
self.steps = steps
self.replacements = 0
async def for_run(self, ctx: RunContext[Any]) -> AbstractCapability[Any]:
# A brand-new instance, the way `dataclasses.replace` builds one: none of the dispatchers a
# durability engine attached to the agent-bound instance ride along on it.
self.replacements += 1
replacement = PerRequestOperation(self.steps)
replacement.replacements = self.replacements
return replacement
async def before_model_request(
self, ctx: RunContext[Any], request_context: ModelRequestContext
) -> ModelRequestContext:
await self.record_step(ctx)
return request_context
@durable_operation('record_step')
async def record_step(self, ctx: RunContext[Any]) -> int:
self.steps.append(ctx.run_step)
return ctx.run_step
class DerivedContextOperation(AbstractCapability[Any]):
"""Dispatches with a context it derived, rather than the one it was handed."""
id = 'derived_context_operation'
def __init__(self) -> None:
self.seen: list[dict[str, Any] | None] = []
async def before_run(self, ctx: RunContext[Any]) -> None:
await self.record(replace(ctx, metadata={'operation': 'reserve'}))
@durable_operation('record')
async def record(self, ctx: RunContext[Any]) -> int:
self.seen.append(ctx.metadata)
return 1
class WrapRunOperation(AbstractCapability[Any]):
"""Calls a durable operation from `wrap_run`, before it awaits the handler."""
id = 'wrap_run_operation'
async def wrap_run(self, ctx: RunContext[Any], *, handler: WrapRunHandler) -> AgentRunResult[Any]:
await self.reserve(ctx)
return await handler()
@durable_operation('reserve')
async def reserve(self, ctx: RunContext[Any]) -> int:
return ctx.run_step
class HoldsSetupContext(AbstractCapability[Any]):
"""Keeps the context `for_run` was handed and dispatches with it from a later hook."""
id = 'holds_setup_context'
def __init__(self) -> None:
self.setup_ctx: RunContext[Any] | None = None
async def for_run(self, ctx: RunContext[Any]) -> AbstractCapability[Any]:
replacement = HoldsSetupContext()
replacement.setup_ctx = ctx
return replacement
async def before_model_request(
self, ctx: RunContext[Any], request_context: ModelRequestContext
) -> ModelRequestContext:
assert self.setup_ctx is not None
await self.read_deps(self.setup_ctx)
return request_context
@durable_operation('read_deps')
async def read_deps(self, ctx: RunContext[Any]) -> str:
return str(ctx.deps)
class BaseHookTier(AbstractCapability[Any]):
@base_hook_durable_operation('provision')
async def provision(self, ctx: RunContext[Any]) -> str: ... # pragma: no branch
class BaseHookOverride(BaseHookTier):
"""An override of a durable base hook, which carries no marker of its own."""
id = 'base_hook_override'
def __init__(self, bodies: list[str]) -> None:
self.bodies = bodies
async def provision(self, ctx: RunContext[Any]) -> str:
self.bodies.append('base')
return 'base'
class BaseHookOverrideReplacement(BaseHookOverride):
async def provision(self, ctx: RunContext[Any]) -> str:
self.bodies.append('replacement')
return 'replacement'
class SpecializedForRun(AbstractCapability[Any]):
"""Replaced for the run by a subclass that overrides the operation, unless kept as-is."""
id = 'specialized_for_run'
def __init__(self, bodies: list[str], *, specialize: bool = True) -> None:
self.bodies = bodies
self.specialize = specialize
async def for_run(self, ctx: RunContext[Any]) -> AbstractCapability[Any]:
return SpecializedForRunReplacement(self.bodies) if self.specialize else self
async def before_model_request(
self, ctx: RunContext[Any], request_context: ModelRequestContext
) -> ModelRequestContext:
await self.describe(ctx)
return request_context
@durable_operation('describe')
async def describe(self, ctx: RunContext[Any]) -> str:
self.bodies.append('base')
return 'base'
class SpecializedForRunReplacement(SpecializedForRun):
@durable_operation('describe')
async def describe(self, ctx: RunContext[Any]) -> str:
self.bodies.append('replacement')
return 'replacement'
class ResolvesInForRun(AbstractCapability[Any]):
"""Calls its own durable operation from `for_run`, before the run has any dispatchers."""
id = 'resolves_in_for_run'
def __init__(self) -> None:
self.calls = 0
async def for_run(self, ctx: RunContext[Any]) -> AbstractCapability[Any]:
await self.resolve(ctx)
return self
@durable_operation('resolve')
async def resolve(self, ctx: RunContext[Any]) -> int:
self.calls += 1
return self.calls
class TenantScopedOperation(AbstractCapability[str]):
id = 'tenant_scoped_operation'
def __init__(self, tenant: str = 'unrestricted', observations: list[str] | None = None) -> None:
self.tenant = tenant
self.observations = observations if observations is not None else []
async def for_run(self, ctx: RunContext[str]) -> AbstractCapability[str]:
return TenantScopedOperation(ctx.deps, self.observations)
async def before_run(self, ctx: RunContext[str]) -> None:
self.observations.append(await self.read_tenant(ctx))
@durable_operation('read_tenant')
async def read_tenant(self, ctx: RunContext[str]) -> str:
return self.tenant
class ModelReadingOperation(AbstractCapability[Any]):
id = 'model_reader'
def __init__(self, expected: TestModel) -> None:
self.expected = expected
self.result = False
async def before_run(self, ctx: RunContext[Any]) -> None:
self.result = await self.read_model(ctx)
@durable_operation('read_model')
async def read_model(self, ctx: RunContext[Any]) -> bool:
return ctx.model is self.expected
class UsageOperation(AbstractCapability[Any]):
id = 'usage_operation'
def __init__(self) -> None:
self.calls = 0
async def before_run(self, ctx: RunContext[Any]) -> None:
await self.record_nested_usage(ctx)
@durable_operation('record_nested_usage')
async def record_nested_usage(self, ctx: RunContext[Any]) -> None:
self.calls += 1
await Agent(TestModel(custom_output_text='summary')).run('summarize', usage=ctx.usage)
ctx.usage.tool_calls += 2
ctx.usage.details['summary_tokens'] = ctx.usage.details.get('summary_tokens', 0) + 3
ctx.usage.details['custom_units'] = ctx.usage.details.get('custom_units', 0) + 7
ctx.usage.cost = (ctx.usage.cost or 0) + Decimal('0.25')
class ProviderCounterUsageOperation(AbstractCapability[Any]):
id = 'provider_counter_usage_operation'
async def before_run(self, ctx: RunContext[Any]) -> None:
await self.record_usage(ctx)
@durable_operation('record_usage')
async def record_usage(self, ctx: RunContext[Any]) -> None:
ctx.usage.incr(
RequestUsage(
cache_write_tokens=6,
cache_write_1h_tokens=4,
output_tokens=5,
output_reasoning_tokens=3,
web_searches=2,
)
)
async def test_non_durable_call_is_direct_and_preserves_identity() -> None:
capability = Operations()
agent = Agent(TestModel(), capabilities=[capability])
await agent.run('test')
assert capability.result == 2
assert capability.calls[0][0].agent is agent
async def test_for_run_replacement_dispatches_on_run_instance() -> None:
replacements: list[PerRunOperation] = []
agent = Agent(
TestModel(),
name='for_run_operation',
capabilities=[PerRunOperation(replacements), RecordingDurability()],
)
await agent.run('test')
assert len(replacements) == 1
assert replacements[0].calls == 1
durability = RecordingDurability.from_agent(agent)
assert durability is not None
assert any(name == 'for_run_operation__capability__per_run_operation.operation' for name, _ in durability.calls)
async def test_per_request_hook_dispatches_on_run_instance() -> None:
"""A per-request hook dispatches durably, even when `for_run` returned a fresh instance.
The operation takes an explicit `RunContext`, which wins over the ambient one, and a hook is
handed a context the graph built for that step rather than the one run setup prepared — so the
per-run dispatchers have to travel with it or the operation silently runs inline.
"""
steps: list[int] = []
agent = Agent(
TestModel(),
name='per_request_operation',
capabilities=[PerRequestOperation(steps), RecordingDurability()],
)
await agent.run('test')
durability = RecordingDurability.from_agent(agent)
assert durability is not None
assert [name for name, _ in durability.calls if '__capability__' in name] == snapshot(
['per_request_operation__capability__per_request_operation.record_step']
)
# The step's own context, not the one run setup prepared, which is still on step 0.
assert steps == snapshot([1])
async def test_per_request_hook_dispatches_on_the_run_instance_it_already_built() -> None:
"""The operation runs as the run's own instance, rather than deriving a second one per call.
Worker-side recovery falls back to re-deriving the per-run instance when the context that
crossed a durable boundary doesn't carry one; in-process it has to reach the instance the run
is already using, or per-run state accumulated by earlier hooks is silently discarded.
"""
capability = PerRequestOperation([])
agent = Agent(
TestModel(),
name='per_request_instance',
capabilities=[capability, RecordingDurability()],
)
await agent.run('test')
assert capability.replacements == snapshot(1)
async def test_operation_receives_the_context_its_caller_passed() -> None:
"""A derived context reaches the operation, and the identity the engine keys on.
The dispatcher forwards whatever context the call supplied rather than the one run setup
prepared, so a caller that narrows or annotates the context is not silently ignored. Engines
whose cache policy hashes the run context therefore key on the derived one -- deliberate, and
the reason this is a documented compatibility impact.
"""
capability = DerivedContextOperation()
agent = Agent(
TestModel(),
name='derived_context_operation',
capabilities=[capability, RecordingDurability()],
)
await agent.run('test')
assert capability.seen == snapshot([{'operation': 'reserve'}])
durability = RecordingDurability.from_agent(agent)
assert durability is not None
keyed = [
next((entry.metadata for entry in key if isinstance(entry, RunContext)), None)
for name, key in durability.calls
if '__capability__' in name
]
assert keyed == snapshot([{'operation': 'reserve'}])
async def test_wrap_run_operation_dispatches_before_the_handler_is_awaited() -> None:
"""`wrap_run` encloses the rest of the run, so dispatch has to exist before the chain is entered.
A wrapper that journals a reservation before awaiting its handler would otherwise perform that
side effect in workflow code, where recovery can repeat it — and a wrapper that short-circuits
never awaits the handler at all.
"""
agent = Agent(
TestModel(),
name='wrap_run_operation',
capabilities=[WrapRunOperation(), RecordingDurability()],
)
await agent.run('test')
durability = RecordingDurability.from_agent(agent)
assert durability is not None
assert [name for name, _ in durability.calls if '__capability__' in name] == snapshot(
['wrap_run_operation__capability__wrap_run_operation.reserve']
)
async def test_operation_dispatches_with_the_context_for_run_was_handed() -> None:
"""The setup context shares the run's mappings, so a capability may keep it and dispatch with it.
`for_run` receives a context built before the graph exists; it has to be the same mapping the run
fills at setup, or an operation called with it later silently runs inline.
"""
agent = Agent(
TestModel(),
name='holds_setup_context',
deps_type=str,
capabilities=[HoldsSetupContext(), RecordingDurability()],
)
await agent.run('test', deps='tenant')
durability = RecordingDurability.from_agent(agent)
assert durability is not None
assert [name for name, _ in durability.calls if '__capability__' in name] == snapshot(
['holds_setup_context__capability__holds_setup_context.read_deps']
)
async def test_dispatch_runs_a_replacement_override_of_a_durable_base_hook() -> None:
"""An override of a durable base hook is specialized per run like a decorated operation is.
Driven through the engine entry point rather than a run: an unmarked base-hook override has no
decorator to dispatch through, so a run reaches it directly and never consults the declaration.
The engine entry point is what a durability integration registers such an operation for, and the
body it binds has to be the one the run's capability implements.
"""
bodies: list[str] = []
model = TestModel()
bound = BaseHookOverride(bodies)
agent = Agent(model, name='base_hook_override', capabilities=[bound, TransparentDurability()])
durability = TransparentDurability.from_agent(agent)
assert durability is not None
ctx = RunContext(deps=None, agent=agent, model=model, usage=RunUsage())
await durability._invoke_capability_operation( # pyright: ignore[reportPrivateUsage]
BaseHookOverrideReplacement(bodies), 'provision', ctx=ctx, args=(ctx,), kwargs={}
)
# And the other direction: the capability the engine bound still contributes its own body.
await durability._invoke_capability_operation( # pyright: ignore[reportPrivateUsage]
bound, 'provision', ctx=ctx, args=(ctx,), kwargs={}
)
assert bodies == snapshot(['replacement', 'base'])
async def test_dispatch_runs_the_replacement_subclass_override() -> None:
"""A specialized `for_run` replacement contributes the body the run executes.
The declaration is collected from the class bound at construction, so dispatching it verbatim
would run the base implementation on the replacement instance — losing the specialization, and
reaching for attributes the replacement may not carry.
"""
bodies: list[str] = []
agent = Agent(
TestModel(),
name='specialized_for_run',
capabilities=[SpecializedForRun(bodies), TransparentDurability()],
)
await agent.run('test')
assert bodies == snapshot(['replacement'])
async def test_dispatch_runs_the_declared_body_when_the_run_keeps_the_instance() -> None:
"""The other direction: with no specialized replacement, the declared body is what runs.
Without this the test above would pass just as well against an implementation that always ran
the capability's own method and never consulted the declaration at all.
"""
bodies: list[str] = []
agent = Agent(
TestModel(),
name='unspecialized_for_run',
capabilities=[SpecializedForRun(bodies, specialize=False), TransparentDurability()],
)
await agent.run('test')
assert bodies == snapshot(['base'])
async def test_operation_called_from_for_run_runs_directly() -> None:
"""`for_run` is what produces the instances dispatch resolves, so it runs before dispatch exists.
An operation called from there runs directly, as it does outside a durable run — pinned because
the capability docs promise it, and because resolving it through the engine instead once meant
`for_run` deriving the instance by calling `for_run`, until the recursion limit.
"""
capability = ResolvesInForRun()
agent = Agent(TestModel(), name='for_run_operation_call', capabilities=[capability, RecordingDurability()])
await agent.run('test')
assert capability.calls == snapshot(1)
durability = RecordingDurability.from_agent(agent)
assert durability is not None
assert [name for name, _ in durability.calls if '__capability__' in name] == snapshot([])
async def test_run_replacement_that_drops_the_bound_id_is_refused() -> None:
"""A replacement under a different `id` leaves the bound operations unreachable.
Dispatch resolves a capability by `id`, so the operations would have run inline and
non-durably instead — the one outcome a durable operation exists to rule out.
"""
class IdChangingOperation(Operations):
id = 'id_changing_operation'
async def for_run(self, ctx: RunContext[Any]) -> AbstractCapability[Any]:
replacement = IdChangingOperation()
replacement.id = 'renamed_for_this_run'
return replacement
agent = Agent(
TestModel(),
name='id_changing',
capabilities=[IdChangingOperation(), RecordingDurability()],
)
with pytest.raises(UserError) as exc_info:
await agent.run('test')
assert str(exc_info.value) == snapshot(
"No capability with id 'id_changing_operation' is present in this run, but one was bound to "
'the agent and contributes durable operations. A `for_run` replacement has to keep the '
"capability's `id`: it identifies the capability across the run, and persisted operation "
'identity and worker-side recovery are built on it.'
)
async def test_shared_capability_dispatch_is_scoped_to_each_agent() -> None:
capability = Operations()
first_agent = Agent(TestModel(), name='first_agent', capabilities=[capability, RecordingDurability()])
second_agent = Agent(TestModel(), name='second_agent', capabilities=[capability, RecordingDurability()])
await first_agent.run('test')
await second_agent.run('test')
first_durability = RecordingDurability.from_agent(first_agent)
second_durability = RecordingDurability.from_agent(second_agent)
assert first_durability is not None and second_durability is not None
assert any(name == 'first_agent__capability__operations.calculate' for name, _ in first_durability.calls)
assert any(name == 'second_agent__capability__operations.calculate' for name, _ in second_durability.calls)
async def test_wrapped_durability_dispatches_capability_operation() -> None:
capability = Operations()
agent = Agent(
TestModel(),
name='wrapped_durability',
capabilities=[capability, WrapperCapability(wrapped=RecordingDurability())],
)
await agent.run('test')
durability = RecordingDurability.from_agent(agent)
assert durability is not None
assert any(name == 'wrapped_durability__capability__operations.calculate' for name, _ in durability.calls)
class ToolCallingOperation(AbstractCapability[Any]):
id = 'tool_calling'
def __init__(self) -> None:
self.calls = 0
@durable_operation('fetch')
async def fetch(self, ctx: RunContext[Any], query: str) -> str:
self.calls += 1
return f'fetched {query}'
def get_toolset(self) -> FunctionToolset[Any]:
toolset = FunctionToolset[Any](id=self.id)
@toolset.tool
async def lookup(ctx: RunContext[Any], query: str) -> str:
return await self.fetch(ctx, query)
return toolset
async def test_operation_called_from_a_wrapped_tool_runs_inside_the_tool_unit() -> None:
"""The tool's unit already records the result, and engines like AWS Lambda can't nest units."""
capability = ToolCallingOperation()
durability = RecordingDurability()
agent = Agent(TestModel(), name='tool_calling', capabilities=[capability, durability])
await agent.run('test')
bound = RecordingDurability.from_agent(agent)
assert bound is not None
names = [name for name, _ in bound.calls]
assert 'tool_calling__function_toolset__tool_calling.call_tool:lookup' in names
assert not [name for name in names if '__capability__' in name]
assert capability.calls == 1
class CallsAnotherCapabilitysOperation(AbstractCapability[Any]):
id = 'tool_owner'
def __init__(self, emitter: EmittingOperation) -> None:
self.emitter = emitter
def get_toolset(self) -> FunctionToolset[Any]:
toolset = FunctionToolset[Any](id=self.id)
@toolset.tool
async def checkpoint(ctx: RunContext[Any]) -> str:
await self.emitter.checkpoint(ctx)
return 'done'
return toolset
async def test_operation_run_inside_another_capabilitys_unit_emits_as_its_own_capability() -> None:
"""Run inline in another capability's tool unit, the operation runs as its own capability, as in its own unit."""
observed: list[str | None] = []
async def observe(ctx: RunContext[Any], stream: AsyncIterable[AgentStreamEvent]) -> None:
async for event in stream:
if isinstance(event, OperationCheckpointEvent):
observed.append(event.capability_id)
emitter = EmittingOperation()
agent = Agent(
TestModel(),
name='cross_capability_emit',
capabilities=[
emitter,
CallsAnotherCapabilitysOperation(emitter),
ProcessEventStream(observe),
RecordingDurability(),
],
)
await agent.run('test')
# Once from `before_run`, outside any unit, and once from the other capability's tool unit.
assert observed == ['emitting_operation', 'emitting_operation']
@requires_temporal
def test_wrapped_temporal_durability_registers_capability_operation() -> None:
agent = Agent(
TestModel(),
name='wrapped_temporal',
capabilities=[Operations(), WrapperCapability(wrapped=TemporalDurability())],
)
durability = TemporalDurability.from_agent(agent)
assert durability is not None
activity_names = {
ActivityDefinition.must_from_callable(activity).name # pyright: ignore[reportUnknownMemberType]
for activity in durability.temporal_activities
}
assert 'agent__wrapped_temporal__capability__operations__calculate' in activity_names
async def test_no_context_operation_is_direct_outside_a_run() -> None:
assert await ContextPositions().no_ctx('outside') == 'outside'
async def test_capability_operation_cache_identity_includes_context_and_model() -> None:
capability = Operations()
capability.arguments = ((3, 4), {'scale': 2, 'bonus': 5})
agent = Agent(TestModel(), name='binding', capabilities=[capability, RecordingDurability()])
await agent.run('test')
assert capability.result == 24
durability = RecordingDurability.from_agent(agent)
assert durability is not None
[(name, inputs)] = [call for call in durability.calls if '__capability__' in call[0]]
assert name == 'binding__capability__operations.calculate'
assert inputs[:2] == (None, {'value': 3, 'extra': [4], 'scale': 2, 'bonus': 5})
assert isinstance(inputs[2], RunContext)
async def test_unmeasured_request_delta_is_applied_once() -> None:
class UnmeasuredRequestOperation(AbstractCapability[None]):
id = 'unmeasured'
async def before_run(self, ctx: RunContext[None]) -> None:
await self.mark(ctx)
@durable_operation('mark')
async def mark(self, ctx: RunContext[None]) -> None:
ctx.usage.unmeasured_requests += 1
agent = Agent(
TestModel(call_tools=[]),
name='unmeasured_usage',
deps_type=type(None),
capabilities=[UnmeasuredRequestOperation(), RecordingDurability()],
)
result = await agent.run('hi')
assert result.usage.unmeasured_requests == 1
async def test_recorded_usage_delta_is_applied_once_per_replayed_run() -> None:
capability = UsageOperation()
agent = Agent(TestModel(), name='replayed_usage', capabilities=[capability, ReplayingDurability()])
results = [await agent.run('test'), await agent.run('test')]
for result in results:
usage = result.usage
assert (
usage.requests,
usage.tool_calls,
usage.details,
usage.cost,
usage.details['custom_units'],
) == (2, 2, {'summary_tokens': 3, 'custom_units': 7}, Decimal('0.25'), 7)
assert capability.calls == 1
async def test_usage_delta_keeps_every_counter() -> None:
"""A replayed durable operation's usage reaches the run total with every counter, not only the common ones.
The operation's usage is recorded as the difference from a snapshot taken before it ran, and a replay
applies that delta to the run. So the subtraction has to keep the one-hour cache writes and reasoning
tokens, and the counters genai-prices extracts without a declared field, like `web_searches`.
"""
agent = Agent(
TestModel(), name='counter_usage', capabilities=[ProviderCounterUsageOperation(), ReplayingDurability()]
)
# The second run replays the operation recorded by the first.
results = [await agent.run('test'), await agent.run('test')]
for result in results:
usage = result.usage
assert (usage.cache_write_tokens, usage.cache_write_1h_tokens) == (6, 4)
assert usage.output_reasoning_tokens == 3
assert getattr(usage, 'web_searches', 0) == 2
@pytest.mark.skipif(not logfire_installed(), reason='logfire not installed')
async def test_replayed_usage_delta_of_an_uninstrumented_delegate_is_not_credited_to_its_caller(
capfire: CaptureLogfire,
) -> None:
"""A delegate without a span doesn't report the usage its replayed operation folds in on the caller's.
On replay the operation's body doesn't run: its recorded usage delta is folded into the delegate's
usage from inside the delegate's run, which must not credit the instrumented run that started it.
"""
capability = UsageOperation()
delegate = Agent(TestModel(), name='delegate', capabilities=[capability, ReplayingDurability()])
parent = Agent(TestModel(), name='parent', capabilities=[Instrumentation()])
@parent.tool_plain
async def ask_delegate() -> str:
return (await delegate.run('x')).output
results = [await parent.run('go'), await parent.run('go')]
assert capability.calls == 1
reported = [
{key: value for key, value in span['attributes'].items() if key.startswith('gen_ai.aggregated_usage.')}
for span in capfire.exporter.exported_spans_as_dict()
if span['name'] == 'invoke_agent parent'
]
# What each parent run spent itself, on both the first run and the replayed one.
assert reported == [
{
'gen_ai.aggregated_usage.input_tokens': result.usage.input_tokens,
'gen_ai.aggregated_usage.output_tokens': result.usage.output_tokens,
}
for result in results
]
@dataclass(kw_only=True)
class OperationCheckpointEvent(CapabilityEvent, namespace='durable_operation_test', name='checkpoint'):
label: str
class EmittingOperation(AbstractCapability[Any]):
id = 'emitting_operation'
def __init__(self) -> None:
self.calls = 0
async def before_run(self, ctx: RunContext[Any]) -> None:
await self.checkpoint(ctx)
@durable_operation('checkpoint')
async def checkpoint(self, ctx: RunContext[Any]) -> None:
self.calls += 1
await ctx.emit(OperationCheckpointEvent(label='one'))
async def test_emit_from_capability_durable_operation_is_not_replayed() -> None:
"""An event emitted inside a `@durable_operation` isn't part of the operation's recorded result.
The operation's body is what emits, so a replayed run gets the recorded return value without the
event. Pinned rather than fixed: the alternative -- rejecting `emit` inside a durable unit the
way `ctx.enqueue()` is rejected -- would stop a capability from reporting what its own operations
do, and unlike an enqueued message a missed event doesn't change what the model sees.
"""
observed: list[str] = []
async def observe(ctx: RunContext[Any], stream: AsyncIterable[AgentStreamEvent]) -> None:
async for event in stream:
if isinstance(event, OperationCheckpointEvent):
observed.append(event.label)
capability = EmittingOperation()
agent = Agent(
TestModel(),
name='replayed_emit',
capabilities=[capability, ProcessEventStream(observe), ReplayingDurability()],
)
await agent.run('test')
await agent.run('test')
assert capability.calls == 1
assert observed == ['one']
def test_decorated_capability_requires_explicit_stable_id() -> None:
class MissingId(AbstractCapability[Any]):
@durable_operation('operation')
async def operation(self, ctx: RunContext[Any]) -> None:
pass
with pytest.raises(UserError, match='needs an explicit `id` because persisted operation identity'):
Agent(TestModel(), name='missing_id', capabilities=[MissingId(), RecordingDurability()])
def test_capability_can_opt_its_id_less_instances_out_of_binding() -> None:
class OptionalId(AbstractCapability[Any]):
_durable_operations_need_id = False
@durable_operation('operation')
async def operation(self, ctx: RunContext[Any]) -> None:
pass # pragma: no cover
agent = Agent(TestModel(), name='optional_id', capabilities=[OptionalId(), RecordingDurability()])
durability = RecordingDurability.from_agent(agent)
assert durability is not None
assert durability._bound_capability_operations == {} # pyright: ignore[reportPrivateUsage]
def test_duplicate_operation_names_fail_during_agent_construction() -> None:
class Duplicate(AbstractCapability[Any]):
id = 'duplicate'
@durable_operation(name='same')
async def first(self, ctx: RunContext[Any]) -> None:
pass
@durable_operation(name='same')
async def second(self, ctx: RunContext[Any]) -> None:
pass
with pytest.raises(UserError, match="Duplicate durable operation name 'same'"):
Agent(TestModel(), name='duplicate', capabilities=[Duplicate(), RecordingDurability()])
@pytest.mark.parametrize(
'hook',
[
'get_toolset',
'get_wrapper_toolset',
'get_wrapper_model',
'wrap_run',
'wrap_node_run',
'wrap_model_request',
'wrap_tool_validate',
'wrap_tool_execute',
'wrap_output_validate',
'wrap_output_process',
'wrap_run_event_stream',
],
)
def test_never_durable_hooks_fail_at_bind(hook: str) -> None:
if hook in ('get_toolset', 'get_wrapper_toolset', 'get_wrapper_model'):
def sync_invalid(self: AbstractCapability[Any], *args: Any, **kwargs: Any) -> None:
return None
invalid: Any = sync_invalid
else:
async def async_invalid(self: AbstractCapability[Any], ctx: RunContext[Any], *args: Any, **kwargs: Any) -> None:
pass
invalid = async_invalid
invalid.__name__ = hook
decorated = durable_operation(hook)(invalid)
capability_type = type('Invalid', (AbstractCapability,), {'id': 'invalid', hook: decorated})
with pytest.raises(UserError, match=f'`{hook}`'):
Agent(TestModel(), name='invalid', capabilities=[capability_type(), RecordingDurability()])
def test_base_hook_override_is_automatically_registered() -> None:
class TierOneBase(AbstractCapability[Any]):
# Registration, not execution, is the behavior under test.
@base_hook_durable_operation('provision')
async def provision(self, ctx: RunContext[Any]) -> str: ... # pragma: no branch
class TierOne(TierOneBase):
id = 'base_hook'
# Automatic registration inspects this override without dispatching it.
async def provision(self, ctx: RunContext[Any]) -> str: ... # pragma: no branch
agent = Agent(TestModel(), name='base_hook', capabilities=[TierOne(), RecordingDurability()])
durability = RecordingDurability.from_agent(agent)
assert durability is not None
assert ('base_hook', 'provision') in durability._bound_capability_operations # pyright: ignore[reportPrivateUsage]
async def test_inherited_base_hook_hook_is_not_registered_or_dispatched() -> None:
class TierOneBase(AbstractCapability[Any]):
def __init__(self) -> None:
self.provisioned = False
@base_hook_durable_operation('provision')
async def provision(self, ctx: RunContext[Any]) -> None:
self.provisioned = True
class TierOne(TierOneBase):
id = 'base_hook'
async def before_run(self, ctx: RunContext[Any]) -> None:
await self.provision(ctx)
capability = TierOne()
assert collect_capability_operations(capability) == {}
agent = Agent(TestModel(), name='base_hook', capabilities=[capability, RecordingDurability()])
await agent.run('test')
durability = RecordingDurability.from_agent(agent)
assert durability is not None
assert capability.provisioned
assert not any('__capability__' in name for name, _ in durability.calls)
@requires_temporal
def test_temporal_registration_has_stable_name_and_types() -> None:
agent = Agent(TestModel(), name='temporal_operations', capabilities=[Operations(), TemporalDurability()])
durability = TemporalDurability.from_agent(agent)
assert durability is not None
registration = next(
activity
for activity in durability.temporal_activities
if ActivityDefinition.must_from_callable(activity).name # pyright: ignore[reportUnknownMemberType]
== 'agent__temporal_operations__capability__operations__calculate'
)
definition = ActivityDefinition.must_from_callable(registration) # pyright: ignore[reportUnknownMemberType]
assert definition.arg_types is not None
assert definition.arg_types[0] is _CapabilityOperationParams
assert definition.ret_type == CapabilityOperationResult[int]
def test_unannotated_parameter_is_rejected_at_bind() -> None:
class Unannotated(AbstractCapability[Any]):
id = 'unannotated'
# Binding rejects the missing annotation before this handler can be dispatched.
@durable_operation('operation')
async def operation( # pragma: no cover
self,
ctx: RunContext[Any],
value, # pyright: ignore[reportMissingParameterType, reportUnknownParameterType]
) -> str: ...
with pytest.raises(UserError, match="Parameter 'value' must have a type annotation"):
Agent(TestModel(), name='unannotated', capabilities=[Unannotated(), RecordingDurability()])
async def test_decorated_model_request_hook_round_trips_request_only_mutation() -> None:
agent = Agent(
TestModel(call_tools=[]),
name='before_model',
capabilities=[DurableBeforeModelRequest(), RecordingDurability()],
)
result = await agent.run('original')
requests = [message for message in result.all_messages() if isinstance(message, ModelRequest)]
assert isinstance(requests[-1].parts[0], UserPromptPart)
assert requests[-1].parts[0].content == 'original'
durability = RecordingDurability.from_agent(agent)
assert durability is not None
assert any(name == 'before_model__capability__before_model.before_model_request' for name, _ in durability.calls)
model_call = next(cache_key for name, cache_key in durability.calls if name == 'before_model__model.request')
sent_request = cast(list[ModelMessage], model_call[1])[-1]
assert isinstance(sent_request, ModelRequest)
assert isinstance(sent_request.parts[0], UserPromptPart)
assert sent_request.parts[0].content == 'replaced'
class RecordModelInBeforeModelRequest(AbstractCapability[Any]):
id = 'record_model'
def __init__(self) -> None:
self.models: list[Model] = []
@durable_operation('before_model_request')
async def before_model_request(
self, ctx: RunContext[Any], request_context: ModelRequestContext
) -> ModelRequestContext:
self.models.append(request_context.model)
return request_context
async def test_decorated_model_request_hook_sees_the_model_before_capabilities_wrap_it() -> None:
"""Model wrappers apply after the `before_model_request` hooks, in the durable unit too."""
recorder = RecordModelInBeforeModelRequest()
batching = BatchModelRequests(**FAST_BATCH_SETTINGS)
agent = Agent(
TestModel(call_tools=[]), name='record_model', capabilities=[recorder, batching, RecordingDurability()]
)
result = await agent.run('Hello')
assert result.output == 'success (no tool calls)'
assert recorder.models
assert not any(isinstance(model, BatchedModel) for model in recorder.models)
async def test_custom_model_request_operation_round_trips_request_only_projection() -> None:
agent = Agent(
TestModel(call_tools=[]),
name='custom_model_request',
capabilities=[CustomModelRequestOperation(), RecordingDurability()],
)
result = await agent.run('original')
requests = [message for message in result.all_messages() if isinstance(message, ModelRequest)]
assert isinstance(requests[-1].parts[0], UserPromptPart)
assert requests[-1].parts[0].content == 'original'
durability = RecordingDurability.from_agent(agent)
assert durability is not None
assert any(
name == 'custom_model_request__capability__custom_model_request.rewrite_request' for name, _ in durability.calls
)
model_call = next(
cache_key for name, cache_key in durability.calls if name == 'custom_model_request__model.request'
)
sent_request = cast(list[ModelMessage], model_call[1])[-1]
assert isinstance(sent_request, ModelRequest)
assert isinstance(sent_request.parts[0], UserPromptPart)
assert sent_request.parts[0].content == 'custom replacement'
async def test_decorated_model_request_hook_round_trips_registered_model_replacement() -> None:
original = TestModel(custom_output_text='original')
restricted = TestModel(custom_output_text='restricted', model_name='restricted')
agent = Agent(
original,
name='model_replacement',
capabilities=[
ModelReplacingBeforeModelRequest(restricted),
RecordingDurability(models={'restricted': restricted}),
],
)
result = await agent.run('test')
assert result.output == 'restricted'
async def test_decorated_model_request_hook_keeps_unchanged_model_resolution_cheap(
monkeypatch: pytest.MonkeyPatch,
) -> None:
model = TestModel(custom_output_text='unchanged')
agent = Agent(model, name='unchanged_model', capabilities=[DurableBeforeModelRequest(), RecordingDurability()])
durability = RecordingDurability.from_agent(agent)
assert durability is not None
resolutions = 0
resolve = durability._resolve_model_for_request # pyright: ignore[reportPrivateUsage]
async def count_resolutions(model_id: str | None, ctx: RunContext[Any]) -> Any:
nonlocal resolutions
resolutions += 1
return await resolve(model_id, ctx)
monkeypatch.setattr(durability, '_resolve_model_for_request', count_resolutions)
result = await agent.run('test')
assert result.output == 'unchanged'
assert resolutions == 2
async def test_decorated_model_request_hook_rejects_unregistered_model_replacement() -> None:
replacement = TestModel(model_name='unregistered')
agent = Agent(
TestModel(),
name='unregistered_model_replacement',
capabilities=[ModelReplacingBeforeModelRequest(replacement), RecordingDurability()],
)
with pytest.raises(
UserError,
match=(
r'A durable `before_model_request` hook replaced `request_context.model` with the unregistered model '
r"instance 'test:unregistered'\. A live `Model` instance cannot be transported across the unit boundary\. "
r'Register it in `models=` on `RecordingDurability` and select that registered model by ID\.'
),
):
await agent.run('test')
async def test_decorated_model_request_hook_rejects_unknown_replacement_model_id() -> None:
model = TestModel()
agent = Agent(
model,
name='unknown_model_replacement',
capabilities=[ModelReplacingBeforeModelRequest(model, model_id='restricted'), RecordingDurability()],
)
with pytest.raises(
UserError,
match=(
r"The model 'restricted' could not be rebuilt on the recording worker: it is not a model name "
r'`infer_model` can build, and no `resolve_model_id` capability claimed it\.'
),
):
await agent.run('test')
async def test_registered_model_replacement_is_stable_on_journal_replay() -> None:
restricted = TestModel(custom_output_text='restricted', model_name='restricted')
capability = ModelReplacingBeforeModelRequest(restricted)
durability = ReplayingDurability(models={'restricted': restricted})
agent = Agent(
TestModel(custom_output_text='original'),
name='replayed_model_replacement',
capabilities=[capability, durability],
)
results = [await agent.run('test'), await agent.run('test')]
assert [result.output for result in results] == ['restricted', 'restricted']
def test_durable_operation_requires_explicit_name() -> None:
async def operation() -> None:
pass
message = (
'`durable_operation` requires an explicit operation name because it becomes persisted compatibility data '
"and must not change when the function is renamed. Use `@durable_operation(name='operation_name')`."
)
with pytest.raises(TypeError, match='^' + re.escape(message) + '$'):
durable_operation(operation) # pyright: ignore[reportArgumentType]
@pytest.mark.parametrize('name', ['', None])
def test_durable_operation_rejects_invalid_name(name: Any) -> None:
if name == '':
with pytest.raises(ValueError, match=re.escape('`durable_operation` name must not be empty')):
durable_operation(name)
else:
with pytest.raises(TypeError, match=re.escape('`durable_operation` name must be a string, got NoneType')):
durable_operation(name)
def test_durable_operation_name_is_independent_of_function_name() -> None:
class Renamed(AbstractCapability[Any]):
id = 'renamed'
@durable_operation(name='operation')
async def renamed_function(self, ctx: RunContext[Any]) -> None:
pass
declarations = collect_capability_operations(Renamed())
assert set(declarations) == {'operation'}
assert (
JournalOperationNamer('agent').operation_name(
CapabilityOperationId('renamed', operation=next(iter(declarations)))
)
== 'agent__capability__renamed.operation'
)
def test_sync_non_hook_operation_is_rejected_by_decorator() -> None:
def operation() -> None:
pass
with pytest.raises(TypeError, match='can only decorate async methods'):
durable_operation('operation')(operation) # pyright: ignore[reportArgumentType]
def test_base_hook_base_and_duplicate_override_paths() -> None:
class Base(AbstractCapability[Any]):
# Collection behavior is tested without dispatching any of these declarations.
@base_hook_durable_operation('operation')
async def operation(self, ctx: RunContext[Any]) -> str: ... # pragma: no branch
sentinel = True
assert collect_capability_operations(Base()) == {}
class Override(Base):
# Collection inspects this override without dispatching it.
async def operation(self, ctx: RunContext[Any]) -> str: ... # pragma: no branch
assert set(collect_capability_operations(Override())) == {'operation'}
async def test_run_context_is_located_from_the_schema() -> None:
capability = ContextPositions()
agent = Agent(TestModel(), name='context_positions', capabilities=[capability, RecordingDurability()])
await agent.run('test')
assert capability.results == [
'first:test',
'last:test',
'keyword:test',
'none',
'previous:2:test',
]
durability = RecordingDurability.from_agent(agent)
assert durability is not None
operation_names = [name for name, _ in durability.calls if '__capability__' in name]
assert operation_names == [
'context_positions__capability__context_positions.ctx_first',
'context_positions__capability__context_positions.ctx_last',
'context_positions__capability__context_positions.ctx_keyword_only',
'context_positions__capability__context_positions.no_ctx',
'context_positions__capability__context_positions.summarize',
]
def test_before_model_request_context_parameter_can_have_any_name() -> None:
declaration = collect_capability_operations(RenamedContextBeforeModelRequest())['before_model_request']
assert declaration.ctx_parameter == 'run_context'
assert declaration.model_request_hook
assert not collect_capability_operations(Operations())['calculate'].model_request_hook
def _define_prepare_capabilities() -> tuple[type[AbstractCapability[Any]], type[AbstractCapability[Any]]]:
"""Define the classes afresh, as Temporal's sandbox does each time it re-imports a workflow module."""
class Prepare(AbstractCapability[Any]):
id = 'prepare'
@durable_operation('before_model_request')
async def before_model_request(
self, ctx: RunContext[Any], request_context: ModelRequestContext
) -> ModelRequestContext:
request_context.messages = [ModelRequest(parts=[UserPromptPart('prepared')])]
return request_context
class PrepareWithNote(AbstractCapability[Any]):
id = 'prepare_with_note'
@durable_operation('rewrite')
async def rewrite(self, ctx: RunContext[Any], request: ModelRequestContext, note: str) -> ModelRequestContext:
raise NotImplementedError
return Prepare, PrepareWithNote
async def test_model_request_operation_schema_is_reused_when_the_capability_is_redefined() -> None:
"""Building an agent with a durable `before_model_request` reuses the request projection's schema.
Generating that schema covers every message type, and a module-level agent in a Temporal workflow
module is rebuilt on every workflow run.
"""
def build_agent() -> Agent[None, str]:
prepare, _ = _define_prepare_capabilities()
return Agent(TestModel(), name='prepare', capabilities=[prepare(), RecordingDurability()])
def declaration(agent: Agent[None, str]) -> CapabilityMethodDeclaration:
durability = RecordingDurability.from_agent(agent)
assert durability is not None
return durability._capability_declarations[('prepare', 'before_model_request')] # pyright: ignore[reportPrivateUsage]
first_agent = build_agent()
second_agent = build_agent()
first, second = declaration(first_agent), declaration(second_agent)
assert first.function is not second.function
assert second.schema.validator is first.schema.validator
assert second.schema.function is not first.schema.function
await second_agent.run('test')
durability = RecordingDurability.from_agent(second_agent)
assert durability is not None
model_call = next(cache_key for name, cache_key in durability.calls if name == 'prepare__model.request')
sent_request = cast(list[ModelMessage], model_call[1])[-1]
assert isinstance(sent_request, ModelRequest)
assert isinstance(sent_request.parts[0], UserPromptPart)
assert sent_request.parts[0].content == 'prepared'
# An operation that also takes a user-typed argument rebuilds its schema every time.
rewrites = [collect_capability_operations(_define_prepare_capabilities()[1]())['rewrite'] for _ in range(2)]
assert rewrites[0].schema.validator is not rewrites[1].schema.validator
@dataclass
class _DocumentedNote:
text: str
"""What the note says."""
class _NoteOperation(AbstractCapability[Any]):
id = 'note_operation'
@durable_operation('read_note')
async def read_note(self, note: _DocumentedNote) -> str:
raise NotImplementedError
def test_operation_schema_reads_no_attribute_docstrings(monkeypatch: pytest.MonkeyPatch) -> None:
"""Building an operation's schema reads no class source for attribute docstrings, unlike a tool's.
Not a VCR test: it builds schemas offline and asserts which class sources Pydantic reads, which no request shows.
Only an operation schema's validator is used. On Python < 3.13, Pydantic re-parses a dataclass's whole module to
read its attribute docstrings (https://github.com/pydantic/pydantic/issues/14309), which takes seconds over every
message type the `ModelRequestContext` projection reaches.
"""
read_classes: list[type] = []
getsourcelines = inspect.getsourcelines
def recording_getsourcelines(cls: type) -> tuple[list[str], int]:
read_classes.append(cls)
return getsourcelines(cls)
monkeypatch.setattr(inspect, 'getsourcelines', recording_getsourcelines)
# An operation that also takes a user-typed argument rebuilds its schema every time, so an earlier test's cached
# schema can't hide a read.
collect_capability_operations(_define_prepare_capabilities()[1]())
# An operation without a run context or a model request context builds its schema on a separate path.
collect_capability_operations(_NoteOperation())
assert read_classes == []
def take_note(note: _DocumentedNote) -> str:
raise NotImplementedError
tool = Tool(take_note)
assert read_classes == [_DocumentedNote]
assert tool.function_schema.json_schema['properties']['text']['description'] == 'What the note says.'
def test_recording_config_has_no_per_tool_override() -> None:
assert (
_RecordingConfig().for_tool(
'tool', CapabilityOperationId('capability', operation='operation'), None, 'operation'
)
== {}
)
def test_two_run_context_parameters_are_rejected_at_bind() -> None:
class DuplicateContext(AbstractCapability[Any]):
id = 'duplicate_context'
@durable_operation('operation')
async def operation(self, first: RunContext[Any], second: RunContext[Any]) -> None:
pass
with pytest.raises(
UserError,
match=r"Durable operation '.*operation' cannot take more than one `RunContext` parameter\.",
):
Agent(TestModel(), name='duplicate_context', capabilities=[DuplicateContext(), RecordingDurability()])
async def test_two_model_request_context_parameters_are_rejected_at_bind() -> None:
class DuplicateModelRequestContext(AbstractCapability[Any]):
id = 'duplicate_model_request_context'
@durable_operation('operation')
async def operation(self, first: ModelRequestContext, second: ModelRequestContext) -> ModelRequestContext:
return first
capability = DuplicateModelRequestContext()
request_context = ModelRequestContext(
model=TestModel(), messages=[], model_settings=None, model_request_parameters=ModelRequestParameters()
)
assert await capability.operation(request_context, request_context) is request_context
with pytest.raises(
UserError,
match=r"Durable operation '.*operation' cannot take more than one `ModelRequestContext` parameter\.",
):
Agent(
TestModel(),
name='duplicate_model_request_context',
capabilities=[capability, RecordingDurability()],
)
def test_variadic_run_context_is_rejected_for_durable_operation() -> None:
class VariadicContext(AbstractCapability[Any]):
id = 'variadic_context'
@durable_operation('operation')
async def operation(self, *ctx: RunContext[Any]) -> None:
pass
with pytest.raises(UserError, match=r'RunContext cannot be used as a variadic positional parameter'):
Agent(TestModel(), name='variadic_context', capabilities=[VariadicContext(), RecordingDurability()])
async def test_variadic_model_request_context_is_rejected_for_durable_operation() -> None:
class VariadicModelRequestContext(AbstractCapability[Any]):
id = 'variadic_model_request_context'
@durable_operation('operation')
async def operation(self, *request_context: ModelRequestContext) -> ModelRequestContext:
return request_context[0]
capability = VariadicModelRequestContext()
request_context = ModelRequestContext(
model=TestModel(), messages=[], model_settings=None, model_request_parameters=ModelRequestParameters()
)
assert await capability.operation(request_context) is request_context
with pytest.raises(UserError, match=r'ModelRequestContext cannot be used as a variadic positional parameter'):
Agent(
TestModel(),
name='variadic_model_request_context',
capabilities=[capability, RecordingDurability()],
)
async def test_defensive_capability_operation_paths() -> None:
capability = Operations()
declaration = collect_capability_operations(capability)['calculate']
projection_declaration = collect_capability_operations(DurableBeforeModelRequest())['before_model_request']
ctx = capability.calls[0][0] if capability.calls else RunContext(deps=None, model=TestModel(), usage=RunUsage())
with pytest.raises(AssertionError, match='called without its model scope'):
await call_declaration(
projection_declaration,
capability,
params=CapabilityOperationParams(ctx, arguments={}),
)
with pytest.raises(RuntimeError, match='requires the worker agent'):
await recover_capability(ctx, capability_id='missing')
plain_agent = Agent(TestModel())
ctx.agent = plain_agent
with pytest.raises(RuntimeError, match='found 0'):
await recover_capability(ctx, capability_id='missing')
assert (
await capability._calculate( # pyright: ignore[reportPrivateUsage]
RunContext(deps=None, model=TestModel(), usage=RunUsage())
)
== 2
)
assert declaration.result_type is int
async def test_bound_dispatch_defensively_rejects_missing_capability_id() -> None:
agent = Agent(TestModel(), name='defensive', capabilities=[RecordingDurability()])
durability = RecordingDurability.from_agent(agent)
assert durability is not None
ctx = RunContext(deps=None, model=TestModel(), usage=RunUsage())
ctx.agent = agent
with pytest.raises(RuntimeError, match='must have an explicit `id`'):
await durability._invoke_capability_operation( # pyright: ignore[reportPrivateUsage]
AbstractCapability(), 'missing', ctx=ctx, args=(), kwargs={}
)
async def test_capability_operation_rejects_realtime_context_model() -> None:
capability = Operations()
agent = Agent(TestModel(), name='realtime_context_model', capabilities=[capability, RecordingDurability()])
durability = RecordingDurability.from_agent(agent)
assert durability is not None
ctx = RunContext(deps=None, agent=agent, model=cast(Any, object()), usage=RunUsage())
with pytest.raises(UserError, match='require a non-realtime `Model` on `RunContext`'):
await durability._invoke_capability_operation( # pyright: ignore[reportPrivateUsage]
capability, 'calculate', ctx=ctx, args=(ctx,), kwargs={}
)
async def test_capability_operation_rejects_unregistered_context_model() -> None:
capability = Operations()
agent = Agent(TestModel(), name='unregistered_context_model', capabilities=[capability, RecordingDurability()])
durability = RecordingDurability.from_agent(agent)
assert durability is not None
ctx = RunContext(deps=None, agent=agent, model=TestModel(), usage=RunUsage())
with pytest.raises(
UserError,
match=r'was not registered with `RecordingDurability`.*cannot be used inside a journal',
):
await durability._invoke_capability_operation( # pyright: ignore[reportPrivateUsage]
capability, 'calculate', ctx=ctx, args=(ctx,), kwargs={}
)
async def test_usage_snapshot_copies_details_before_in_place_handler_mutation() -> None:
"""`RunUsage.__copy__` isolates its only mutable field before worker-side accounting."""
usage = RunUsage(details={'existing': 2})
before = copy.copy(usage)
ctx = RunContext(deps=None, model=TestModel(), usage=usage)
async def handler(ctx: RunContext[None]) -> None:
ctx.usage.details['existing'] += 3
await handler(ctx)
assert before.details == {'existing': 2}
assert before.details is not usage.details
assert (usage - before).details == {'existing': 3}
@requires_temporal
async def test_temporal_capability_transport_and_summary(monkeypatch: pytest.MonkeyPatch) -> None:
capability = Operations()
agent = Agent(TestModel(), name='temporal_transport', capabilities=[capability, TemporalDurability()])
durability = TemporalDurability.from_agent(agent)
assert durability is not None
declaration = durability._capability_declarations[('operations', 'calculate')] # pyright: ignore[reportPrivateUsage]
transport = _CapabilityOperationTransport(durability, declaration)
ctx = RunContext(deps=None, model=TestModel(), usage=RunUsage())
ctx.agent = agent
params = CapabilityOperationParams(ctx, arguments={'value': 2, 'extra': [], 'scale': 1})
wire, deps = transport.dump(params)
assert isinstance(wire, _CapabilityOperationParams)
loaded = transport.load((wire, deps), runtime=durability)
assert loaded.arguments == params.arguments
summaries: list[str] = []
async def execute_activity(*, activity: Any, args: Any, **config: Any) -> int:
summaries.append(config['summary'])
return 2
monkeypatch.setattr('pydantic_ai.durable_exec.temporal._operation_backend.execute_activity', execute_activity)
bound = durability._bound_capability_operations[('operations', 'calculate')] # pyright: ignore[reportPrivateUsage]
assert await bound(params) == 2
assert summaries == ['capability: operations.calculate']
@requires_temporal
async def test_temporal_capability_operation_resolves_ctx_model_worker_side() -> None:
model = TestModel()
capability = ModelReadingOperation(model)
agent = Agent(model, name='temporal_model_reader', capabilities=[capability, TemporalDurability()])
durability = TemporalDurability.from_agent(agent)
assert durability is not None
declaration = durability._capability_declarations[('model_reader', 'read_model')] # pyright: ignore[reportPrivateUsage]
transport = _CapabilityOperationTransport(durability, declaration)
ctx = RunContext(deps=None, agent=agent, model=model, usage=RunUsage())
wire, deps = transport.dump(CapabilityOperationParams(ctx, arguments={}, model_id=None))
registration = next(
activity
for activity in durability.temporal_activities
if ActivityDefinition.must_from_callable(activity).name # pyright: ignore[reportUnknownMemberType]
== 'agent__temporal_model_reader__capability__model_reader__read_model'
)
assert await registration(wire, deps)
@requires_temporal
async def test_temporal_capability_operation_rederives_for_run_instance_worker_side() -> None:
capability = TenantScopedOperation()
agent = Agent(
TestModel(),
name='temporal_tenant_scope',
deps_type=str,
capabilities=[capability, TemporalDurability()],
)
durability = TemporalDurability.from_agent(agent)
assert durability is not None
declaration = durability._capability_declarations[ # pyright: ignore[reportPrivateUsage]
('tenant_scoped_operation', 'read_tenant')
]
transport = _CapabilityOperationTransport(durability, declaration)
ctx = RunContext(deps='tenant-a', agent=agent, model=TestModel(), usage=RunUsage())
wire, deps = transport.dump(CapabilityOperationParams(ctx, arguments={}))
registration = next(
activity
for activity in durability.temporal_activities
if ActivityDefinition.must_from_callable(activity).name # pyright: ignore[reportUnknownMemberType]
== 'agent__temporal_tenant_scope__capability__tenant_scoped_operation__read_tenant'
)
result = await registration(wire, deps)
assert result.value == 'tenant-a'
assert capability.tenant == 'unrestricted'
@requires_temporal
async def test_temporal_capability_operation_projects_registered_model_replacement() -> None:
original = TestModel(model_name='original')
restricted = TestModel(model_name='restricted')
capability = ModelReplacingBeforeModelRequest(restricted)
agent = Agent(
original,
name='temporal_model_replacement',
capabilities=[capability, TemporalDurability(models={'restricted': restricted})],
)
durability = TemporalDurability.from_agent(agent)
assert durability is not None
declaration = durability._capability_declarations[ # pyright: ignore[reportPrivateUsage]
('model_replacing_before_model', 'before_model_request')
]
transport = _CapabilityOperationTransport(durability, declaration)
ctx = RunContext(deps=None, agent=agent, model=original, usage=RunUsage())
projection = ModelRequestContextProjection(
[],
model_settings=None,
model_request_parameters=ModelRequestParameters(),
model_id=None,
streaming=False,
)
wire, deps = transport.dump(CapabilityOperationParams(ctx, arguments={'request_context': projection}))
registration = next(
activity
for activity in durability.temporal_activities
if ActivityDefinition.must_from_callable(activity).name # pyright: ignore[reportUnknownMemberType]
== 'agent__temporal_model_replacement__capability__model_replacing_before_model__before_model_request'
)
result = await registration(wire, deps)
assert result.value.model_id == 'restricted'
@pytest.fixture
def dbos(tmp_path: Any) -> Generator[DBOS, None, None]:
config: DBOSConfig = {
'name': 'capability_durable_operations',
'system_database_url': f'sqlite:///{tmp_path / "dbos.sqlite"}',
}
instance = DBOS(config=config)
DBOS.launch()
try:
yield instance
finally:
DBOS.destroy()
@requires_dbos
async def test_dbos_capability_operation_end_to_end(dbos: DBOS) -> None:
model = TestModel()
capability = Operations()
model_reader = ModelReadingOperation(model)
agent = Agent(model, name='dbos_operations', capabilities=[capability, model_reader, DBOSDurability()])
workflow_id = str(uuid.uuid4())
@DBOS.workflow(name=f'capability_operations_{workflow_id}')
async def workflow() -> int:
await agent.run('test')
assert capability.result is not None
return capability.result
with SetWorkflowID(workflow_id):
assert await workflow() == 2
assert model_reader.result
steps = await dbos.list_workflow_steps_async(workflow_id)
assert 'dbos_operations__capability__operations.calculate' in [step['function_name'] for step in steps]
@requires_dbos
async def test_dbos_capability_operation_uses_for_run_instance_in_registered_step(dbos: DBOS) -> None:
observations: list[str] = []
capability = TenantScopedOperation(observations=observations)
agent = Agent(
TestModel(),
name='dbos_tenant_scope',
deps_type=str,
capabilities=[capability, DBOSDurability()],
)
workflow_id = str(uuid.uuid4())
@DBOS.workflow(name=f'capability_tenant_scope_{workflow_id}')
async def workflow() -> None:
await agent.run('test', deps='tenant-a')
with SetWorkflowID(workflow_id):
await workflow()
assert observations == ['tenant-a']
assert capability.tenant == 'unrestricted'
@requires_dbos
async def test_dbos_capability_usage_delta_is_stable_on_replay(dbos: DBOS) -> None:
capability = UsageOperation()
agent = Agent(TestModel(), name='dbos_usage', capabilities=[capability, DBOSDurability()])
workflow_id = str(uuid.uuid4())
@DBOS.workflow(name=f'capability_usage_{workflow_id}')
async def workflow() -> tuple[int, int, dict[str, int], Decimal | None, int]:
result = await agent.run('test')
usage = result.usage
return usage.requests, usage.tool_calls, usage.details, usage.cost, usage.details['custom_units']
with SetWorkflowID(workflow_id):
first = await workflow()
with SetWorkflowID(workflow_id):
replayed = await workflow()
assert first == replayed == (2, 2, {'summary_tokens': 3, 'custom_units': 7}, Decimal('0.25'), 7)
assert capability.calls == 1
@requires_prefect
@pytest.mark.xdist_group(name='prefect')
async def test_prefect_capability_operation_end_to_end(prefect_test_server: None) -> None:
capability = Operations()
agent = Agent(TestModel(), name='prefect_operations', capabilities=[capability, PrefectDurability()])
@flow
async def run() -> int:
await agent.run('test')
assert capability.result is not None
return capability.result
assert await run() == 2
@requires_prefect
@pytest.mark.xdist_group(name='prefect')
async def test_prefect_capability_operation_cache_identity_includes_context_and_model(
prefect_test_server: None,
) -> None:
class CacheIdentityOperation(AbstractCapability[str]):
id = 'cache_identity'
def __init__(self) -> None:
self.calls: list[tuple[str, str]] = []
async def before_run(self, ctx: RunContext[str]) -> None:
await self.read_context(ctx, 1)
@durable_operation('read_context')
async def read_context(self, ctx: RunContext[str], value: int) -> None:
self.calls.append((ctx.deps, ctx.model.model_name))
capability = CacheIdentityOperation()
alternative_model = TestModel(custom_output_text='alternative', model_name='alternative')
agent = Agent[str, str](
TestModel(),
name='prefect_capability_cache_identity',
deps_type=str,
capabilities=[capability, PrefectDurability(models={'alternative': alternative_model})],
)
@flow
async def run() -> None:
await agent.run('same', deps='tenant-a')
await agent.run('same', deps='tenant-a')
await agent.run('same', deps='tenant-b')
await agent.run('same', deps='tenant-b', model='alternative')
await run()
assert capability.calls == [
('tenant-a', 'test'),
('tenant-a', 'test'),
('tenant-b', 'test'),
('tenant-b', 'alternative'),
]
async def test_file_understanding_describes_through_the_engine() -> None:
"""`FileUnderstanding` asks another model to describe a file, so that call is a durable operation."""
seen: list[list[ModelMessage]] = []
def capture(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
seen.append(messages)
return ModelResponse(parts=[TextPart('ok')])
def describe(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
return ModelResponse(parts=[TextPart('A field guide.')])
text_only = FunctionModel(capture, profile=ModelProfile(supports_document_input=False))
agent = Agent(
text_only,
name='file_understanding_run',
capabilities=[FileUnderstanding(fallback_subagent_model=FunctionModel(describe)), RecordingDurability()],
)
result = await agent.run([DocumentUrl('https://example.com/guide.pdf')])
# The describing request crossed the durable boundary and still counts toward the run's usage.
assert result.usage.requests == 2
durability = RecordingDurability.from_agent(agent)
assert durability is not None
assert [name for name, _ in durability.calls if '__capability__' in name] == snapshot(
['file_understanding_run__capability__file_understanding.describe']
)
part = seen[-1][-1].parts[-1]
assert isinstance(part, UserPromptPart)
[content] = part.content
assert isinstance(content, str) and 'A field guide.' in content
async def test_file_understanding_reads_a_recorded_description_instead_of_describing_again() -> None:
"""The description is in the history, so a run that continues it schedules no `describe` operation.
This is what keeps a recovered or replayed workflow's operations in line with its recorded ones: whether a file
is described depends on the history the run is given, not on what other runs in the process did before.
"""
def describe(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
return ModelResponse(parts=[TextPart('A field guide.')])
def agent() -> Agent[None, str]:
text_only = FunctionModel(
lambda messages, info: ModelResponse(parts=[TextPart('ok')]),
profile=ModelProfile(supports_document_input=False),
)
return Agent(
text_only,
name='file_understanding_run',
capabilities=[FileUnderstanding(fallback_subagent_model=FunctionModel(describe)), RecordingDurability()],
)
first = await agent().run([DocumentUrl('https://example.com/guide.pdf')])
# A fresh agent and engine, as a restarted worker would have.
continued = agent()
await continued.run('And again?', message_history=first.all_messages())
durability = RecordingDurability.from_agent(continued)
assert durability is not None
assert [name for name, _ in durability.calls if '__capability__' in name] == []