Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

27.3 KB
Raw Blame
import asyncio
import json
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch

import aiohttp
import httpx
import msgpack
import numpy as np
import pytest
from sie_sdk import LoraLoadingError, ModelLoadingError, ProvisioningError, ServerError, SIEAsyncClient, SIEClient
from sie_sdk.client._shared import (
    DEFAULT_CONNECT_TIMEOUT_S,
    DEFAULT_PROVISION_TIMEOUT_S,
    DEFAULT_READ_TIMEOUT_S,
    LORA_LOADING_MAX_RETRIES,
)
from sie_sdk.client.async_ import _AioResponse

_REFUSAL_HEADERS = {
    "X-SIE-Request-ID": "req-refused",
    "X-SIE-Served-By": "local",
    "X-SIE-Fallback-Reason": "provisioning",
    "X-SIE-Fallback-Error": "QUEUE_FULL",
}
_REFUSAL_METADATA = {
    "id": "req-refused",
    "served_by": "local",
    "fallback_reason": "provisioning",
    "fallback_error": "QUEUE_FULL",
}
_CAPACITY_READY_AT_S = 700.0


class _Clock:
    """Monotonic clock that advances only when the client sleeps."""

    def __init__(self) -> None:
        self.now = 0.0
        self.sleeps: list[float] = []

    def monotonic(self) -> float:
        return self.now

    def sleep(self, seconds: float) -> None:
        self.sleeps.append(seconds)
        self.now += seconds


class _ClockAsyncio:
    """The ``asyncio`` module as the async client sees it, sleeping on the fake clock."""

    def __init__(self, clock: _Clock) -> None:
        self._clock = clock

    def __getattr__(self, name: str) -> Any:
        return getattr(asyncio, name)

    async def sleep(self, seconds: float, result: Any = None) -> Any:
        self._clock.sleep(seconds)
        return result


@pytest.fixture
def clock(monkeypatch: pytest.MonkeyPatch) -> _Clock:
    fake = _Clock()
    monkeypatch.setattr("sie_sdk.client.sync.time", fake)
    monkeypatch.setattr("sie_sdk.client.async_.time", fake)
    monkeypatch.setattr("sie_sdk.client._shared.time", fake)
    monkeypatch.setattr("sie_sdk.client.async_.asyncio", _ClockAsyncio(fake))
    return fake


def _refusal_body(code: str) -> dict[str, Any]:
    return {"error": {"code": code, "message": "Capacity for model 'bge-m3' is starting."}}


def _sync_refusal(code: str, retry_after: str = "900") -> MagicMock:
    response = MagicMock()
    response.status_code = 503
    response.headers = {"content-type": "application/json", "Retry-After": retry_after, **_REFUSAL_HEADERS}
    response.json.return_value = _refusal_body(code)
    response.content = json.dumps(_refusal_body(code)).encode()
    return response


def _sync_encoded() -> MagicMock:
    response = MagicMock()
    response.status_code = 200
    response.headers = {"content-type": "application/msgpack"}
    response.content = msgpack.packb({"items": [{"dense": {"dims": 4, "values": np.zeros(4)}}]}, use_bin_type=True)
    return response


def _async_refusal(code: str, retry_after: str = "900") -> _AioResponse:
    return _AioResponse(
        503,
        json.dumps(_refusal_body(code)).encode(),
        {"content-type": "application/json", "Retry-After": retry_after, **_REFUSAL_HEADERS},
    )


def _async_encoded() -> _AioResponse:
    return _AioResponse(
        200,
        msgpack.packb({"items": [{"dense": {"dims": 4, "values": np.zeros(4)}}]}, use_bin_type=True),
        {"content-type": "application/msgpack"},
    )


class TestProvisioningRetry:
    """Tests for 503 PROVISIONING retry functionality."""

    def test_machine_profile_header_sent_when_gpu_specified(self) -> None:
        """X-SIE-MACHINE-PROFILE header is sent when gpu parameter provided."""
        mock_response = MagicMock()
        mock_response.status_code = 200
        mock_response.headers = {"content-type": "application/msgpack"}
        mock_response.content = msgpack.packb({"items": [{"dense": {"values": np.zeros(1024)}}]}, use_bin_type=True)

        with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
            mock_client.return_value.post = MagicMock(return_value=mock_response)
            client = SIEClient("http://localhost:8080")

            client.encode("bge-m3", {"text": "hello"}, gpu="l4")

            # Check that X-SIE-MACHINE-PROFILE header was sent
            call_args = mock_client.return_value.post.call_args
            assert call_args.kwargs["headers"]["X-SIE-MACHINE-PROFILE"] == "l4"
            client.close()

    def test_503_provisioning_raises_provisioning_error_without_wait(self) -> None:
        """503 PROVISIONING raises ProvisioningError when wait_for_capacity=False."""
        from sie_sdk import ProvisioningError
        from sie_sdk.client._shared import PROVISIONING_ERROR_CODE

        mock_response = MagicMock()
        mock_response.status_code = 503
        mock_response.headers = {"Retry-After": "30", "content-type": "application/json"}
        mock_response.json.return_value = {
            "error": {"code": PROVISIONING_ERROR_CODE, "message": "Server is provisioning"}
        }

        with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
            mock_client.return_value.post = MagicMock(return_value=mock_response)
            client = SIEClient("http://localhost:8080")

            with pytest.raises(ProvisioningError) as exc_info:
                client.encode("bge-m3", {"text": "hello"}, gpu="l4", wait_for_capacity=False)

            assert exc_info.value.gpu == "l4"
            assert exc_info.value.retry_after == 30.0
            client.close()

    def test_503_provisioning_retries_with_wait_for_capacity(self) -> None:
        """503 PROVISIONING is retried when wait_for_capacity=True."""
        from sie_sdk.client._shared import PROVISIONING_ERROR_CODE

        # First response is 503 PROVISIONING, second is 200
        mock_response_503 = MagicMock()
        mock_response_503.status_code = 503
        mock_response_503.headers = {"Retry-After": "0.01", "content-type": "application/json"}
        mock_response_503.json.return_value = {
            "error": {"code": PROVISIONING_ERROR_CODE, "message": "Server is provisioning"}
        }

        mock_response_200 = MagicMock()
        mock_response_200.status_code = 200
        mock_response_200.headers = {"content-type": "application/msgpack"}
        mock_response_200.content = msgpack.packb({"items": [{"dense": {"values": np.zeros(1024)}}]}, use_bin_type=True)

        with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
            mock_client.return_value.post = MagicMock(side_effect=[mock_response_503, mock_response_200])
            client = SIEClient("http://localhost:8080")

            result = client.encode(
                "bge-m3",
                {"text": "hello"},
                gpu="l4",
                wait_for_capacity=True,
                provision_timeout_s=0.2,
            )

            # Should have retried and succeeded
            assert "dense" in result
            assert mock_client.return_value.post.call_count == 2
            assert client.last_retry_count == 1
            client.close()

    def test_503_provisioning_timeout_raises_provisioning_error(self) -> None:
        """Provisioning timeout raises ProvisioningError."""
        from sie_sdk import ProvisioningError
        from sie_sdk.client._shared import PROVISIONING_ERROR_CODE

        mock_response_503 = MagicMock()
        mock_response_503.status_code = 503
        mock_response_503.headers = {"Retry-After": "0.01", "content-type": "application/json"}
        mock_response_503.json.return_value = {
            "error": {"code": PROVISIONING_ERROR_CODE, "message": "Server is provisioning"}
        }

        with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
            # Always return 503 PROVISIONING
            mock_client.return_value.post = MagicMock(return_value=mock_response_503)
            client = SIEClient("http://localhost:8080")

            with pytest.raises(ProvisioningError) as exc_info:
                client.encode(
                    "bge-m3",
                    {"text": "hello"},
                    gpu="l4",
                    wait_for_capacity=True,
                    provision_timeout_s=0.05,  # Very short timeout
                )

            assert "timeout" in str(exc_info.value).lower()
            client.close()

    def test_retry_after_header_parsed(self) -> None:
        """Retry-After header is correctly parsed."""
        from sie_sdk import ProvisioningError
        from sie_sdk.client._shared import PROVISIONING_ERROR_CODE

        mock_response = MagicMock()
        mock_response.status_code = 503
        mock_response.headers = {"Retry-After": "60", "content-type": "application/json"}
        mock_response.json.return_value = {
            "error": {"code": PROVISIONING_ERROR_CODE, "message": "Server is provisioning"}
        }

        with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
            mock_client.return_value.post = MagicMock(return_value=mock_response)
            client = SIEClient("http://localhost:8080")

            with pytest.raises(ProvisioningError) as exc_info:
                client.encode("bge-m3", {"text": "hello"}, gpu="l4", wait_for_capacity=False)

            assert exc_info.value.retry_after == 60.0
            client.close()

    def test_missing_retry_after_uses_default(self) -> None:
        """Missing Retry-After header uses None."""
        from sie_sdk import ProvisioningError
        from sie_sdk.client._shared import PROVISIONING_ERROR_CODE

        mock_response = MagicMock()
        mock_response.status_code = 503
        mock_response.headers = {"content-type": "application/json"}  # No Retry-After
        mock_response.json.return_value = {
            "error": {"code": PROVISIONING_ERROR_CODE, "message": "Server is provisioning"}
        }

        with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
            mock_client.return_value.post = MagicMock(return_value=mock_response)
            client = SIEClient("http://localhost:8080")

            with pytest.raises(ProvisioningError) as exc_info:
                client.encode("bge-m3", {"text": "hello"}, gpu="l4", wait_for_capacity=False)

            assert exc_info.value.retry_after is None
            client.close()

    def test_default_wait_for_capacity_is_true(self) -> None:
        """Default wait_for_capacity is True, so 503 PROVISIONING is retried automatically."""
        from sie_sdk.client._shared import PROVISIONING_ERROR_CODE

        mock_response_503 = MagicMock()
        mock_response_503.status_code = 503
        mock_response_503.headers = {"Retry-After": "0.01", "content-type": "application/json"}
        mock_response_503.json.return_value = {
            "error": {"code": PROVISIONING_ERROR_CODE, "message": "Server is provisioning"}
        }

        mock_response_200 = MagicMock()
        mock_response_200.status_code = 200
        mock_response_200.headers = {"content-type": "application/msgpack"}
        mock_response_200.content = msgpack.packb({"items": [{"dense": {"values": np.zeros(1024)}}]}, use_bin_type=True)

        with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
            mock_client.return_value.post = MagicMock(side_effect=[mock_response_503, mock_response_200])
            client = SIEClient("http://localhost:8080")

            # No explicit wait_for_capacity -- default should be True now
            result = client.encode(
                "bge-m3",
                {"text": "hello"},
                gpu="l4",
                provision_timeout_s=0.2,
            )

            assert "dense" in result
            assert mock_client.return_value.post.call_count == 2
            client.close()

    def test_explicit_wait_for_capacity_false_still_works(self) -> None:
        """Explicitly setting wait_for_capacity=False raises ProvisioningError on 503 PROVISIONING."""
        from sie_sdk import ProvisioningError
        from sie_sdk.client._shared import PROVISIONING_ERROR_CODE

        mock_response = MagicMock()
        mock_response.status_code = 503
        mock_response.headers = {"Retry-After": "30", "content-type": "application/json"}
        mock_response.json.return_value = {
            "error": {"code": PROVISIONING_ERROR_CODE, "message": "Server is provisioning"}
        }

        with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
            mock_client.return_value.post = MagicMock(return_value=mock_response)
            client = SIEClient("http://localhost:8080")

            with pytest.raises(ProvisioningError):
                client.encode("bge-m3", {"text": "hello"}, gpu="l4", wait_for_capacity=False)

            client.close()


class TestModelLoadingRetry:
    """Tests for 503 MODEL_LOADING retry functionality."""

    def test_503_model_loading_retries_until_success(self) -> None:
        """503 with MODEL_LOADING error code is retried until model is loaded."""
        from sie_sdk.client._shared import MODEL_LOADING_ERROR_CODE

        # First response is 503 MODEL_LOADING, second is 200
        mock_response_503 = MagicMock()
        mock_response_503.status_code = 503
        mock_response_503.headers = {"Retry-After": "0.01", "content-type": "application/json"}
        mock_response_503.json.return_value = {"detail": {"code": MODEL_LOADING_ERROR_CODE, "message": "Model loading"}}

        mock_response_200 = MagicMock()
        mock_response_200.status_code = 200
        mock_response_200.headers = {"content-type": "application/msgpack"}
        mock_response_200.content = msgpack.packb(
            {"items": [{"dense": {"dims": 4, "values": np.zeros(4)}}]}, use_bin_type=True
        )

        with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
            mock_client.return_value.post = MagicMock(side_effect=[mock_response_503, mock_response_200])
            client = SIEClient("http://localhost:8080")

            result = client.encode("bge-m3", {"text": "hello"})

            # Should have retried and succeeded
            assert "dense" in result
            assert mock_client.return_value.post.call_count == 2
            client.close()

    def test_503_model_loading_timeout_raises_error(self) -> None:
        """MODEL_LOADING retry timeout raises timeout error after provision_timeout_s exceeded.

        Either ModelLoadingError (timeout during retry) or ProvisioningError
        (pre-request timeout check) are valid - both indicate the timeout was enforced.
        """
        from sie_sdk import ModelLoadingError, ProvisioningError
        from sie_sdk.client._shared import MODEL_LOADING_ERROR_CODE

        mock_response_503 = MagicMock()
        mock_response_503.status_code = 503
        mock_response_503.headers = {"Retry-After": "0.01", "content-type": "application/json"}
        mock_response_503.json.return_value = {"detail": {"code": MODEL_LOADING_ERROR_CODE, "message": "Model loading"}}

        with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
            # Always return 503 MODEL_LOADING
            mock_client.return_value.post = MagicMock(return_value=mock_response_503)
            client = SIEClient("http://localhost:8080")

            # Use a very short provision_timeout_s to trigger timeout quickly
            with pytest.raises((ModelLoadingError, ProvisioningError)) as exc_info:
                client.encode("bge-m3", {"text": "hello"}, provision_timeout_s=0.05)

            assert "timeout" in str(exc_info.value).lower()
            client.close()

    def test_503_non_model_loading_not_retried(self) -> None:
        """503 without MODEL_LOADING code raises ServerError immediately."""
        mock_response_503 = MagicMock()
        mock_response_503.status_code = 503
        mock_response_503.headers = {"content-type": "application/json"}
        mock_response_503.json.return_value = {"error": {"code": "OVERLOADED", "message": "Server overloaded"}}

        with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
            mock_client.return_value.post = MagicMock(return_value=mock_response_503)
            client = SIEClient("http://localhost:8080")

            with pytest.raises(ServerError) as exc_info:
                client.encode("bge-m3", {"text": "hello"}, wait_for_capacity=False)

            assert exc_info.value.status_code == 503
            assert exc_info.value.code == "OVERLOADED"
            # Should not have retried
            assert mock_client.return_value.post.call_count == 1
            client.close()

    def test_model_loading_retry_respects_retry_after_header(self) -> None:
        """MODEL_LOADING retry uses Retry-After header value."""
        from sie_sdk.client._shared import MODEL_LOADING_ERROR_CODE

        mock_response_503 = MagicMock()
        mock_response_503.status_code = 503
        mock_response_503.headers = {"Retry-After": "0.05", "content-type": "application/json"}
        mock_response_503.json.return_value = {"detail": {"code": MODEL_LOADING_ERROR_CODE, "message": "Model loading"}}

        mock_response_200 = MagicMock()
        mock_response_200.status_code = 200
        mock_response_200.headers = {"content-type": "application/msgpack"}
        mock_response_200.content = msgpack.packb(
            {"items": [{"dense": {"dims": 4, "values": np.zeros(4)}}]}, use_bin_type=True
        )

        with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
            mock_client.return_value.post = MagicMock(side_effect=[mock_response_503, mock_response_200])
            with patch("sie_sdk.client.sync.time.sleep") as mock_sleep:
                client = SIEClient("http://localhost:8080")
                client.encode("bge-m3", {"text": "hello"})

                # Should have slept with the Retry-After value
                mock_sleep.assert_called_with(0.05)
            client.close()


class TestAsyncModelLoadingRetry:
    """Tests for async 503 MODEL_LOADING retry functionality."""

    @pytest.mark.asyncio
    async def test_503_model_loading_retries_until_success(self) -> None:
        """503 with MODEL_LOADING error code is retried until model is loaded."""
        from sie_sdk.client._shared import MODEL_LOADING_ERROR_CODE
        from sie_sdk.client.async_ import _AioResponse

        resp_503 = _AioResponse(
            503,
            json.dumps({"detail": {"code": MODEL_LOADING_ERROR_CODE, "message": "Model loading"}}).encode(),
            {"Retry-After": "0.01", "content-type": "application/json"},
        )
        resp_200 = _AioResponse(
            200,
            msgpack.packb({"items": [{"dense": {"dims": 4, "values": np.zeros(4)}}]}, use_bin_type=True),
            {"content-type": "application/msgpack"},
        )

        client = SIEAsyncClient("http://localhost:8080")
        client._post = AsyncMock(side_effect=[resp_503, resp_200])  # type: ignore

        result = await client.encode("bge-m3", {"text": "hello"})

        assert "dense" in result
        assert client._post.call_count == 2
        await client.close()

    @pytest.mark.asyncio
    async def test_503_model_loading_timeout_raises_error(self) -> None:
        """MODEL_LOADING retry timeout raises timeout error after provision_timeout_s exceeded."""
        from sie_sdk import ModelLoadingError, ProvisioningError
        from sie_sdk.client._shared import MODEL_LOADING_ERROR_CODE
        from sie_sdk.client.async_ import _AioResponse

        resp_503 = _AioResponse(
            503,
            json.dumps({"detail": {"code": MODEL_LOADING_ERROR_CODE, "message": "Model loading"}}).encode(),
            {"Retry-After": "0.01", "content-type": "application/json"},
        )

        client = SIEAsyncClient("http://localhost:8080")
        client._post = AsyncMock(return_value=resp_503)  # type: ignore

        with pytest.raises((ModelLoadingError, ProvisioningError)) as exc_info:
            await client.encode("bge-m3", {"text": "hello"}, provision_timeout_s=0.05)

        assert "timeout" in str(exc_info.value).lower()
        await client.close()


class TestFinalAttemptAtBudgetEnd:
    """A capacity wait that reaches the end of the budget is followed by one final attempt."""

    @pytest.mark.parametrize("code", ["PROVISIONING", "MODEL_LOADING"])
    def test_sync_capacity_ready_during_the_last_wait_is_used(self, clock: _Clock, code: str) -> None:
        def post(*_args: object, **_kwargs: object) -> MagicMock:
            return _sync_encoded() if clock.now >= _CAPACITY_READY_AT_S else _sync_refusal(code)

        with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
            mock_client.return_value.post = MagicMock(side_effect=post)
            client = SIEClient("http://localhost:8080")

            result = client.encode("bge-m3", {"text": "hello"})

            assert "dense" in result
            assert clock.sleeps == [DEFAULT_PROVISION_TIMEOUT_S]
            assert mock_client.return_value.post.call_count == 2
            assert client.last_retry_count == 1
            final_attempt = mock_client.return_value.post.call_args
            assert final_attempt.kwargs["timeout"] == httpx.Timeout(
                DEFAULT_READ_TIMEOUT_S, connect=DEFAULT_CONNECT_TIMEOUT_S
            )
            client.close()

    @pytest.mark.parametrize("code", ["PROVISIONING", "MODEL_LOADING"])
    async def test_async_capacity_ready_during_the_last_wait_is_used(self, clock: _Clock, code: str) -> None:
        async def post(*_args: object, **_kwargs: object) -> _AioResponse:
            return _async_encoded() if clock.now >= _CAPACITY_READY_AT_S else _async_refusal(code)

        client = SIEAsyncClient("http://localhost:8080")
        client._post = AsyncMock(side_effect=post)  # type: ignore[method-assign]

        result = await client.encode("bge-m3", {"text": "hello"})

        assert "dense" in result
        assert clock.sleeps == [DEFAULT_PROVISION_TIMEOUT_S]
        assert client._post.call_count == 2
        assert client.last_retry_count == 1
        assert client._post.call_args.kwargs["client_timeout"] == aiohttp.ClientTimeout(
            total=DEFAULT_READ_TIMEOUT_S,
            connect=DEFAULT_READ_TIMEOUT_S,
            sock_connect=DEFAULT_CONNECT_TIMEOUT_S,
            sock_read=DEFAULT_READ_TIMEOUT_S,
        )
        await client.close()

    def test_sync_final_attempt_still_provisioning_raises_provisioning_error(self, clock: _Clock) -> None:
        with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
            mock_client.return_value.post = MagicMock(side_effect=lambda *_a, **_k: _sync_refusal("PROVISIONING"))
            client = SIEClient("http://localhost:8080")

            with pytest.raises(ProvisioningError) as excinfo:
                client.encode("bge-m3", {"text": "hello"}, gpu="l4")

            assert mock_client.return_value.post.call_count == 2
            client.close()

        assert clock.sleeps == [DEFAULT_PROVISION_TIMEOUT_S]
        error = excinfo.value
        assert str(error) == "Provisioning timeout after 900.0s waiting for GPU 'l4'"
        assert (error.gpu, error.retry_after, error.request) == ("l4", 900.0, _REFUSAL_METADATA)

    async def test_async_final_attempt_still_provisioning_raises_provisioning_error(self, clock: _Clock) -> None:
        client = SIEAsyncClient("http://localhost:8080")
        client._post = AsyncMock(side_effect=lambda *_a, **_k: _async_refusal("PROVISIONING"))  # type: ignore[method-assign]

        with pytest.raises(ProvisioningError) as excinfo:
            await client.encode("bge-m3", {"text": "hello"}, gpu="l4")

        assert client._post.call_count == 2
        assert clock.sleeps == [DEFAULT_PROVISION_TIMEOUT_S]
        error = excinfo.value
        assert str(error) == "Provisioning timeout after 900.0s waiting for GPU 'l4'"
        assert (error.gpu, error.retry_after, error.request) == ("l4", 900.0, _REFUSAL_METADATA)
        await client.close()

    def test_sync_final_attempt_still_loading_raises_model_loading_error(self, clock: _Clock) -> None:
        with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
            mock_client.return_value.post = MagicMock(side_effect=lambda *_a, **_k: _sync_refusal("MODEL_LOADING"))
            client = SIEClient("http://localhost:8080")

            with pytest.raises(ModelLoadingError) as excinfo:
                client.encode("bge-m3", {"text": "hello"})

            assert mock_client.return_value.post.call_count == 2
            client.close()

        assert clock.sleeps == [DEFAULT_PROVISION_TIMEOUT_S]
        assert (excinfo.value.model, excinfo.value.request) == ("bge-m3", _REFUSAL_METADATA)

    async def test_async_final_attempt_still_loading_raises_model_loading_error(self, clock: _Clock) -> None:
        client = SIEAsyncClient("http://localhost:8080")
        client._post = AsyncMock(side_effect=lambda *_a, **_k: _async_refusal("MODEL_LOADING"))  # type: ignore[method-assign]

        with pytest.raises(ModelLoadingError) as excinfo:
            await client.encode("bge-m3", {"text": "hello"})

        assert client._post.call_count == 2
        assert clock.sleeps == [DEFAULT_PROVISION_TIMEOUT_S]
        assert (excinfo.value.model, excinfo.value.request) == ("bge-m3", _REFUSAL_METADATA)
        await client.close()


class TestRefusalRequestMetadata:
    """Provisioning, model-loading and LoRA-loading errors carry the refusal's request metadata."""

    def test_sync_provisioning_without_waiting(self) -> None:
        with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
            mock_client.return_value.post = MagicMock(return_value=_sync_refusal("PROVISIONING", retry_after="30"))
            client = SIEClient("http://localhost:8080")

            with pytest.raises(ProvisioningError) as excinfo:
                client.encode("bge-m3", {"text": "hello"}, wait_for_capacity=False)

            assert mock_client.return_value.post.call_count == 1
            client.close()

        assert (excinfo.value.retry_after, excinfo.value.request) == (30.0, _REFUSAL_METADATA)

    async def test_async_provisioning_without_waiting(self) -> None:
        client = SIEAsyncClient("http://localhost:8080")
        client._post = AsyncMock(return_value=_async_refusal("PROVISIONING", retry_after="30"))  # type: ignore[method-assign]

        with pytest.raises(ProvisioningError) as excinfo:
            await client.encode("bge-m3", {"text": "hello"}, wait_for_capacity=False)

        assert client._post.call_count == 1
        assert (excinfo.value.retry_after, excinfo.value.request) == (30.0, _REFUSAL_METADATA)
        await client.close()

    def test_sync_lora_loading_retries_exhausted(self, clock: _Clock) -> None:
        with patch("sie_sdk.client.sync.httpx.Client") as mock_client:
            mock_client.return_value.post = MagicMock(side_effect=lambda *_a, **_k: _sync_refusal("LORA_LOADING", "1"))
            client = SIEClient("http://localhost:8080")

            with pytest.raises(LoraLoadingError) as excinfo:
                client.encode("bge-m3", {"text": "hello"}, options={"lora": "adapter-a"})

            assert mock_client.return_value.post.call_count == LORA_LOADING_MAX_RETRIES + 1
            client.close()

        error = excinfo.value
        assert (error.lora, error.model, error.request) == ("adapter-a", "bge-m3", _REFUSAL_METADATA)

    async def test_async_lora_loading_retries_exhausted(self, clock: _Clock) -> None:
        client = SIEAsyncClient("http://localhost:8080")
        client._post = AsyncMock(side_effect=lambda *_a, **_k: _async_refusal("LORA_LOADING", "1"))  # type: ignore[method-assign]

        with pytest.raises(LoraLoadingError) as excinfo:
            await client.encode("bge-m3", {"text": "hello"}, options={"lora": "adapter-a"})

        assert client._post.call_count == LORA_LOADING_MAX_RETRIES + 1
        error = excinfo.value
        assert (error.lora, error.model, error.request) == ("adapter-a", "bge-m3", _REFUSAL_METADATA)
        await client.close()