From 7200b2608c4d86721541ef55d28c074d6c404853 Mon Sep 17 00:00:00 2001 From: Andrey Buzin Date: Mon, 16 Nov 2026 13:24:10 -0800 Subject: [PATCH] Make HookDeferredException survive pickle and copy The default exception reducer reconstructs from args, which holds the hook id. The constructor needs the HookPart instead, so unpickling and copying raised AttributeError. Serialize the hook and instance state explicitly. Keep the exception arguments and text unchanged, and test pickle, shallow copy, deep copy, and exception notes. --- src/ai/agents/hooks.py | 11 ++++++++++- tests/agents/test_hooks.py | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/ai/agents/hooks.py b/src/ai/agents/hooks.py index 049ac0ae..dde85b45 100644 --- a/src/ai/agents/hooks.py +++ b/src/ai/agents/hooks.py @@ -33,7 +33,7 @@ from . import runtime as runtime_ if TYPE_CHECKING: - from collections.abc import AsyncIterator + from collections.abc import AsyncIterator, Callable class HookRegistry: @@ -141,6 +141,15 @@ def __init__( super().__init__(hook.hook_id) self.hook = hook + def __reduce__( + self, + ) -> tuple[ + Callable[..., HookDeferredException], + tuple[messages_.HookPart[Any]], + dict[str, Any], + ]: + return type(self), (self.hook,), self.__dict__ + def _label(target: str | messages_.HookPart[Any]) -> str: """Normalize a hook label or a HookPart down to its label string.""" diff --git a/tests/agents/test_hooks.py b/tests/agents/test_hooks.py index 2f449f36..90ec9448 100644 --- a/tests/agents/test_hooks.py +++ b/tests/agents/test_hooks.py @@ -3,6 +3,8 @@ from __future__ import annotations import asyncio +import copy +import pickle from collections.abc import AsyncGenerator from typing import Any @@ -20,6 +22,22 @@ class Confirmation(pydantic.BaseModel): reason: str = "" +def test_hook_deferred_exception_survives_pickle_and_copy() -> None: + hook: ai.messages.HookPart[Any] = ai.messages.HookPart( + hook_id="approve_tc-1", hook_type="ToolApproval", status="pending" + ) + exc = ai.HookDeferredException(hook) + exc.add_note("keep exception state") + + restored = pickle.loads(pickle.dumps(exc)) + assert restored.hook == hook + assert copy.copy(exc).hook == hook + assert copy.deepcopy(exc).hook == hook + assert restored.args == exc.args == (hook.hook_id,) + assert str(restored) == str(exc) == hook.hook_id + assert restored.__notes__ == ["keep exception state"] + + # -- resolve_hook() with live future (long-running mode) -------------------