From 5758181b8a833748831ef6a8d1e12e37f66b362a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurent=20Rivi=C3=A8re?= <26854828+superlevure@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:13:04 +0100 Subject: [PATCH] fix(graphql): await retry backoff in AsyncGraphQL instead of blocking AsyncGraphQL.execute waited between retries with the blocking time.sleep used by the synchronous clients, freezing the event loop for the whole retry sequence (up to ~100 s with the default max_retries, or a full Retry-After on a 429). Add Retry.async_handle_retry_on_status, which shares the wait time computation with handle_retry_on_status but awaits anyio.sleep (asyncio and trio), and use it in AsyncGraphQL.execute. Closes #3471 --- gitlab/client.py | 2 +- gitlab/utils.py | 45 ++++++++++++++++++++++++++++++++------ tests/unit/test_graphql.py | 25 +++++++++++++++++++++ tests/unit/test_retry.py | 29 ++++++++++++++++++++++++ 4 files changed, 93 insertions(+), 8 deletions(-) diff --git a/gitlab/client.py b/gitlab/client.py index f6fe89d84..3668dd0f8 100644 --- a/gitlab/client.py +++ b/gitlab/client.py @@ -1439,7 +1439,7 @@ async def execute(self, request: str, *args: Any, **kwargs: Any) -> Any: parsed_document, *args, **kwargs ) except gql.transport.exceptions.TransportServerError as e: - if retry.handle_retry_on_status( + if await retry.async_handle_retry_on_status( status_code=e.code, headers=self._transport.response_headers ): continue diff --git a/gitlab/utils.py b/gitlab/utils.py index 49a280278..c0f3556c7 100644 --- a/gitlab/utils.py +++ b/gitlab/utils.py @@ -114,14 +114,15 @@ def _retryable_status_code(self, status_code: int | None, reason: str = "") -> b return False - def handle_retry_on_status( + def _get_wait_time_on_status( self, status_code: int | None, headers: MutableMapping[str, str] | None = None, reason: str = "", - ) -> bool: + ) -> float | None: + """Return how long to wait before retrying, or None to not retry.""" if not self._retryable_status_code(status_code, reason): - return False + return None if headers is None: headers = {} @@ -129,16 +130,46 @@ def handle_retry_on_status( # Response headers documentation: # https://docs.gitlab.com/ee/user/admin_area/settings/user_and_ip_rate_limits.html#response-headers if self.max_retries == -1 or self.cur_retries < self.max_retries: - wait_time = 2**self.cur_retries * 0.1 + wait_time: float = 2**self.cur_retries * 0.1 if "Retry-After" in headers: wait_time = int(headers["Retry-After"]) elif "RateLimit-Reset" in headers: wait_time = max(0, int(headers["RateLimit-Reset"]) - time.time()) self.cur_retries += 1 - time.sleep(wait_time) - return True + return wait_time - return False + return None + + def handle_retry_on_status( + self, + status_code: int | None, + headers: MutableMapping[str, str] | None = None, + reason: str = "", + ) -> bool: + wait_time = self._get_wait_time_on_status(status_code, headers, reason) + if wait_time is None: + return False + + time.sleep(wait_time) + return True + + async def async_handle_retry_on_status( + self, + status_code: int | None, + headers: MutableMapping[str, str] | None = None, + reason: str = "", + ) -> bool: + """Like handle_retry_on_status, without blocking the event loop.""" + # anyio ships with httpx (the graphql extra) and supports both asyncio + # and trio; imported here as the synchronous clients do not need it. + import anyio + + wait_time = self._get_wait_time_on_status(status_code, headers, reason) + if wait_time is None: + return False + + await anyio.sleep(wait_time) + return True def handle_retry(self) -> bool: if self.retry_transient_errors and ( diff --git a/tests/unit/test_graphql.py b/tests/unit/test_graphql.py index 9348dbf98..bbdc60256 100644 --- a/tests/unit/test_graphql.py +++ b/tests/unit/test_graphql.py @@ -1,3 +1,6 @@ +import time +from unittest import mock + import httpx import pytest import respx @@ -99,6 +102,28 @@ async def test_async_graphql_raises_when_max_retries_exceeded( await gl_async_gql.execute("query {currentUser {id}}") +@pytest.mark.anyio +async def test_async_graphql_retries_without_blocking_event_loop( + api_url: str, respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch +): + mock_sleep = mock.Mock() + monkeypatch.setattr(time, "sleep", mock_sleep) + responses = [ + httpx.Response(502), + httpx.Response( + 200, json={"data": {"currentUser": {"id": "gid://gitlab/User/1"}}} + ), + ] + respx_mock.post(api_url).mock(side_effect=responses) + + gl_async_gql = gitlab.AsyncGraphQL( + "https://gitlab.example.com", max_retries=1, retry_transient_errors=True + ) + await gl_async_gql.execute("query {currentUser {id}}") + + mock_sleep.assert_not_called() + + def test_graphql_raises_on_401_response( api_url: str, gl_gql: gitlab.GraphQL, respx_mock: respx.MockRouter ): diff --git a/tests/unit/test_retry.py b/tests/unit/test_retry.py index 811dc4249..af60abcf8 100644 --- a/tests/unit/test_retry.py +++ b/tests/unit/test_retry.py @@ -1,6 +1,7 @@ import time from unittest import mock +import anyio import pytest from gitlab import utils @@ -39,3 +40,31 @@ def test_handle_retry_on_status_accepts_ratelimit_reset_header( def test_handle_retry_on_status_returns_false_when_max_retries_reached(): retry = utils.Retry(max_retries=0) assert retry.handle_retry_on_status(429) is False + + +@pytest.mark.anyio +async def test_async_handle_retry_on_status_ignores_unknown_status_code(): + retry = utils.Retry(max_retries=1, retry_transient_errors=True) + assert await retry.async_handle_retry_on_status(418) is False + + +@pytest.mark.anyio +async def test_async_handle_retry_on_status_awaits_sleep( + monkeypatch: pytest.MonkeyPatch, +): + mock_sleep = mock.Mock() + mock_async_sleep = mock.AsyncMock() + monkeypatch.setattr(time, "sleep", mock_sleep) + monkeypatch.setattr(anyio, "sleep", mock_async_sleep) + retry = utils.Retry(max_retries=1) + headers = {"Retry-After": "1"} + + assert await retry.async_handle_retry_on_status(429, headers=headers) is True + mock_async_sleep.assert_awaited_once_with(1) + mock_sleep.assert_not_called() + + +@pytest.mark.anyio +async def test_async_handle_retry_on_status_returns_false_when_max_retries_reached(): + retry = utils.Retry(max_retries=0) + assert await retry.async_handle_retry_on_status(429) is False