diff --git a/src/ai/errors.py b/src/ai/errors.py index c30db8ee..7c4c7703 100644 --- a/src/ai/errors.py +++ b/src/ai/errors.py @@ -286,6 +286,11 @@ 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, ...]: + # 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__ + 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..6be16b26 100644 --- a/src/ai/models/core/helpers/files.py +++ b/src/ai/models/core/helpers/files.py @@ -45,6 +45,11 @@ def __init__( if cause is not None: self.__cause__ = cause + def __reduce__(self) -> tuple[object, ...]: + # 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} + 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"