Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/ai/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
5 changes: 5 additions & 0 deletions src/ai/models/core/helpers/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
67 changes: 67 additions & 0 deletions tests/models/core/helpers/test_files.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
19 changes: 19 additions & 0 deletions tests/test_errors.py
Original file line number Diff line number Diff line change
@@ -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"
Loading