From b2cdaaf853fbc6bbca18fbfd93bf9da543025f0a Mon Sep 17 00:00:00 2001 From: Andrey Buzin Date: Mon, 16 Nov 2026 13:24:12 -0800 Subject: [PATCH 1/2] Preserve exception messages through pickle and copy UnsupportedProviderError and DownloadError take an identifier or URL in their constructors, but store formatted text in Exception.args. The default pickle and copy paths pass that text back into the constructors and format it again. Restore each error from its original constructor argument and instance state. Keep the download error's formatted args so status text survives. Continue to omit causes, so an unpicklable cause does not prevent a copy. Cover pickle and deep copy, including status details and an unpicklable cause. --- src/ai/errors.py | 3 ++ src/ai/models/core/helpers/files.py | 4 ++ tests/models/core/helpers/test_files.py | 67 +++++++++++++++++++++++++ tests/test_errors.py | 19 +++++++ 4 files changed, 93 insertions(+) create mode 100644 tests/test_errors.py diff --git a/src/ai/errors.py b/src/ai/errors.py index c30db8ee..aeff69b1 100644 --- a/src/ai/errors.py +++ b/src/ai/errors.py @@ -286,6 +286,9 @@ def __init__(self, provider_id: str) -> None: self.provider_id = provider_id super().__init__(f"unsupported provider {provider_id!r}") + def __reduce__(self) -> tuple[object, ...]: + return type(self), (self.provider_id,), self.__dict__ + def http_status_to_provider_status_error_class( status_code: int, diff --git a/src/ai/models/core/helpers/files.py b/src/ai/models/core/helpers/files.py index 94a340a2..47fa0672 100644 --- a/src/ai/models/core/helpers/files.py +++ b/src/ai/models/core/helpers/files.py @@ -45,6 +45,10 @@ def __init__( if cause is not None: self.__cause__ = cause + def __reduce__(self) -> tuple[object, ...]: + # Preserve the formatted message, including keyword-only status details. + return type(self), (self.url,), {**self.__dict__, "args": self.args} + def _validate_address(address: str, url: str) -> None: """Allow only public unicast addresses, including embedded IPv4 targets.""" diff --git a/tests/models/core/helpers/test_files.py b/tests/models/core/helpers/test_files.py index 289f120d..2311de44 100644 --- a/tests/models/core/helpers/test_files.py +++ b/tests/models/core/helpers/test_files.py @@ -1,9 +1,12 @@ from __future__ import annotations import asyncio +import copy import gzip +import pickle import socket import ssl +import threading from collections.abc import AsyncIterator from typing import Any from unittest import mock @@ -474,3 +477,67 @@ async def test_url_passthrough_and_inline_media_unchanged(network: Any) -> None: ] == "data:image/png;base64,aW1hZ2U=" dns.assert_not_called() send.assert_not_called() + + +def test_download_error_preserves_message_and_attributes() -> None: + """Pickle and deep copy preserve the URL, status, and formatted text.""" + error = files.DownloadError("https://example.com/a.png", status_code=404) + + assert ( + str(error) + == "Failed to download 'https://example.com/a.png': status=404" + ) + for restored in (pickle.loads(pickle.dumps(error)), copy.deepcopy(error)): + assert type(restored) is type(error) + assert str(restored) == str(error) + assert restored.args == error.args + assert restored.__dict__ == error.__dict__ + assert restored.url == "https://example.com/a.png" + assert restored.status_code == 404 + + +@pytest.mark.parametrize( + ("status_code", "status_text"), + [(None, None), (404, "Not Found"), (None, "connection reset")], +) +def test_download_error_preserves_status_text( + status_code: int | None, status_text: str | None +) -> None: + error = files.DownloadError( + "https://example.com/a.png", + status_code=status_code, + status_text=status_text, + cause=ValueError("connection closed"), + ) + + for restored in (pickle.loads(pickle.dumps(error)), copy.deepcopy(error)): + assert type(restored) is type(error) + assert str(restored) == str(error) + assert restored.args == error.args + assert restored.__dict__ == error.__dict__ + assert restored.url == error.url + assert restored.status_code == status_code + assert restored.__cause__ is None + + +def test_download_error_ignores_unpicklable_cause() -> None: + cause = ValueError(threading.Lock()) + with pytest.raises(TypeError): + pickle.dumps(cause) + with pytest.raises(TypeError): + copy.deepcopy(cause) + error = files.DownloadError( + "https://example.com/a.png", + status_text="connection failed", + cause=cause, + ) + + for restored in (pickle.loads(pickle.dumps(error)), copy.deepcopy(error)): + assert type(restored) is type(error) + assert str(restored) == str(error) + assert restored.args == error.args + assert restored.__dict__ == error.__dict__ + assert restored.url == error.url + assert restored.status_code == error.status_code + assert restored.__cause__ is None + assert error.__cause__ is cause diff --git a/tests/test_errors.py b/tests/test_errors.py new file mode 100644 index 00000000..ea982144 --- /dev/null +++ b/tests/test_errors.py @@ -0,0 +1,19 @@ +from __future__ import annotations + +import copy +import pickle + +import ai + + +def test_unsupported_provider_error_preserves_message_and_attributes() -> None: + """Pickle and deep copy preserve the provider ID and formatted text.""" + error = ai.UnsupportedProviderError("zzz") + + assert str(error) == "unsupported provider 'zzz'" + for restored in (pickle.loads(pickle.dumps(error)), copy.deepcopy(error)): + assert type(restored) is type(error) + assert str(restored) == str(error) + assert restored.args == error.args + assert restored.__dict__ == error.__dict__ + assert restored.provider_id == "zzz" From 06ea5de36e84f0704f65be161d04d7748b0e70b3 Mon Sep 17 00:00:00 2001 From: Andrey Buzin Date: Thu, 19 Nov 2026 11:43:42 -0800 Subject: [PATCH 2/2] Address review --- src/ai/errors.py | 2 ++ src/ai/models/core/helpers/files.py | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/ai/errors.py b/src/ai/errors.py index aeff69b1..7c4c7703 100644 --- a/src/ai/errors.py +++ b/src/ai/errors.py @@ -287,6 +287,8 @@ def __init__(self, provider_id: str) -> None: super().__init__(f"unsupported provider {provider_id!r}") def __reduce__(self) -> tuple[object, ...]: + # Pickle and copy need the provider ID, not the formatted message, + # to avoid formatting the message twice. return type(self), (self.provider_id,), self.__dict__ diff --git a/src/ai/models/core/helpers/files.py b/src/ai/models/core/helpers/files.py index 47fa0672..6be16b26 100644 --- a/src/ai/models/core/helpers/files.py +++ b/src/ai/models/core/helpers/files.py @@ -46,7 +46,8 @@ def __init__( self.__cause__ = cause def __reduce__(self) -> tuple[object, ...]: - # Preserve the formatted message, including keyword-only status details. + # Pickle and copy need the URL, not the formatted message. + # Restore args to keep the keyword-only status details in the message. return type(self), (self.url,), {**self.__dict__, "args": self.args}