Skip to content

[python] honor Configuration.retries in the httpx client - #25820

Open
b2l wants to merge 3 commits into
OpenAPITools:masterfrom
LeComptoirDesPharmacies:fix/python-httpx-retries
Open

b2l wants to merge 3 commits into
OpenAPITools:masterfrom
LeComptoirDesPharmacies:fix/python-httpx-retries

Conversation

@b2l

@b2l b2l commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #25801

Configuration.retries is documented for the httpx library but ignored by rest.py.
This PR passes it to httpx's own retry mechanism, AsyncHTTPTransport(retries=...),
without working around httpx's limits and without breaking existing setups.

Behavior

Configuration Before After
retries unset, 0 or negative no retry unchanged
retries > 0, direct connection no retry (bug) connection failures retried
retries > 0 + Configuration.proxy proxy, no retry unchanged
retries > 0 + proxy from environment (HTTP(S)_PROXY, ALL_PROXY) proxy, no retry unchanged

httpx retries only ConnectError/ConnectTimeout (the request was never sent), so this
is safe for all HTTP methods, unlike the asyncio client which restricts retries to
ALLOW_RETRY_METHODS.

Why retries are limited to direct connections

With a proxy, httpx's transport retries bring nothing and have a side effect:

  1. httpx does not retry through a proxy: AsyncHTTPTransport does not forward retries
    to AsyncHTTPProxy/AsyncSOCKSProxy (Fixing missed arguments for pools when init transports encode/httpx#2997, open). Checked with httpx
    0.28.1 and httpx2 2.16.2: retries=2 gives 3 connection attempts directly, 1 through
    a proxy.
  2. A custom transport disables proxies from environment variables
    (allow_env_proxies = trust_env and transport is None, encode/httpx discussion [BUG] okhttp-gson generation on windows creates a uncompilable build.gradle #2593).
    Building it would send requests directly instead of through the proxy.

So the retry transport is only built when there is no proxy: no Configuration.proxy
and none from the environment, detected with urllib.request.getproxies() (what httpx
reads as well; NO_PROXY alone does not count). Otherwise the client is built exactly as
before. This is documented in the Configuration docstring, together with the fact that
each attempt gets the full connect timeout, with httpcore's backoff between attempts
(0 s, 0.5 s, 1 s…).

If encode/httpx#2997 is fixed, the proxy condition can be revisited.

Changes

  • python/httpx/rest.mustache: _create_pool_manager() builds
    AsyncHTTPTransport(retries=..., verify=..., limits=...) when retries > 0 and no
    proxy is set.
  • python/configuration.mustache: document what retries covers for httpx.
  • Samples regenerated: python-httpx, python-httpx-sync, python-httpx2,
    python-httpx2-sync.
  • New tests/test_retries.py in these four samples:
    • retries=2 against a closed port: 3 real connection attempts, counted at
      anyio.connect_tcp;
    • retries unset, 0, -1: 1 attempt, and the client is built as before;
    • retries=3: TLS context and connection limit go to the transport; NO_PROXY alone
      keeps the retries;
    • retries=3 with Configuration.proxy, or with HTTP_PROXY, https_proxy or
      ALL_PROXY in the environment: the client is built as before.

Testing

  • On master, the retry tests fail and the "built as before" tests pass (they pin the
    current behavior).
  • With this change, all of them pass (httpx 0.28.1, httpx2 2.16.2).
  • The other failures in these samples are unchanged from master: test_pet_api.py
    needs the petstore server, and mypy reports the same error in signing.py.

PR checklist

  • Read the contribution guidelines.
  • Built the CLI (./mvnw clean package -DskipTests -pl modules/openapi-generator-cli -am, template-only change) and ran ./bin/generate-samples.sh on the four bin/configs/python-httpx*.yaml configs, committed all changed files. No generator option changed, so the generator docs are unaffected.
  • @mention the Python technical committee: @cbornet @tomplus @krjakbrjak @fa0311 @AndreyVMarkelov

🤖 Generated with Claude Code

Configuration.retries is documented for the httpx library but rest.py never
read it. Pass it to AsyncHTTPTransport(retries=...): httpx only retries
connection failures, so it is safe for every method.

The transport is only built when retries is set: a custom transport disables
proxies from environment variables, and a client-level proxy would bypass it,
so the explicit proxy goes to the transport.

Fixes OpenAPITools#25801

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 14 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="samples/openapi3/client/petstore/python-httpx/petstore_api/rest.py">

<violation number="1" location="samples/openapi3/client/petstore/python-httpx/petstore_api/rest.py:207">
P2: With retries enabled, each connect attempt gets the full timeout, so an unreachable host can block for up to (retries + 1) × timeout plus backoff. That breaks the total-timeout contract documented in `request()`. Document this behavior, or enforce an overall deadline.</violation>
</file>

Reply to a comment to ask cubic a question or push back. It learns from your replies.

View guided diff | Re-trigger cubic

verify=self.ssl_context,
limits=limits,
proxy=proxy,
retries=self.retries,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: With retries enabled, each connect attempt gets the full timeout, so an unreachable host can block for up to (retries + 1) × timeout plus backoff. That breaks the total-timeout contract documented in request(). Document this behavior, or enforce an overall deadline.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At samples/openapi3/client/petstore/python-httpx/petstore_api/rest.py, line 207:

<comment>With retries enabled, each connect attempt gets the full timeout, so an unreachable host can block for up to (retries + 1) × timeout plus backoff. That breaks the total-timeout contract documented in `request()`. Document this behavior, or enforce an overall deadline.</comment>

<file context>
@@ -193,6 +195,22 @@ def _create_pool_manager(self) -> httpx.AsyncClient:
+                verify=self.ssl_context,
+                limits=limits,
+                proxy=proxy,
+                retries=self.retries,
+            )
+            return httpx.AsyncClient(
</file context>

- Only build the retry transport for a positive retries count.
- Document httpx's limits instead of working around them: proxies from
  environment variables are ignored with a custom transport, and requests
  sent through a proxy are not retried (encode/httpx#2997). Each attempt
  gets the full connect timeout.
- Tests count real connection attempts instead of transport kwargs, and
  cover retries=0 and negative values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 14 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="samples/openapi3/client/petstore/python-httpx/tests/test_retries.py">

<violation number="1" location="samples/openapi3/client/petstore/python-httpx/tests/test_retries.py:15">
P2: This helper releases the selected port before the request starts, creating a race with other processes that can make the retry-count assertions flaky. Keep the reservation lifecycle through the connection attempt or use a deterministic local failure mechanism.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

def closed_port():
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This helper releases the selected port before the request starts, creating a race with other processes that can make the retry-count assertions flaky. Keep the reservation lifecycle through the connection attempt or use a deterministic local failure mechanism.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At samples/openapi3/client/petstore/python-httpx/tests/test_retries.py, line 15:

<comment>This helper releases the selected port before the request starts, creating a race with other processes that can make the retry-count assertions flaky. Keep the reservation lifecycle through the connection attempt or use a deterministic local failure mechanism.</comment>

<file context>
@@ -1,24 +1,57 @@
+def closed_port():
+    with socket.socket() as sock:
+        sock.bind(("127.0.0.1", 0))
+        return sock.getsockname()[1]
+
+
</file context>

httpx does not retry through a proxy (encode/httpx#2997), and a custom
transport disables proxies from environment variables. Building the retry
transport with a proxy brought no retry and broke environment proxies.

Only build it for direct connections: no Configuration.proxy and no proxy
from the environment (urllib.request.getproxies, as httpx does). Otherwise
the client is built as before, so this change is not breaking.

Tests pin that behavior for explicit and environment proxies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 14 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="samples/openapi3/client/petstore/python-httpx2/tests/test_retries.py">

<violation number="1" location="samples/openapi3/client/petstore/python-httpx2/tests/test_retries.py:48">
P3: These added test lines exceed the repository’s configured 99-character Flake8 limit, so the sample fails lint when Flake8 is run. Wrap the docstring, mock context, assertions, and proxy test context across lines.</violation>
</file>

<file name="samples/openapi3/client/petstore/python-httpx/tests/test_retries.py">

<violation number="1" location="samples/openapi3/client/petstore/python-httpx/tests/test_retries.py:48">
P3: Several added lines exceed this sample’s configured 99-character flake8 limit, causing lint failures when flake8 runs. Wrap the helper, patch, assertion, and context-manager lines to keep each line within the configured limit.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

@@ -0,0 +1,104 @@
"""Configuration.retries is passed to httpx2's transport retries, for direct connections."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: These added test lines exceed the repository’s configured 99-character Flake8 limit, so the sample fails lint when Flake8 is run. Wrap the docstring, mock context, assertions, and proxy test context across lines.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At samples/openapi3/client/petstore/python-httpx2/tests/test_retries.py, line 48:

<comment>These added test lines exceed the repository’s configured 99-character Flake8 limit, so the sample fails lint when Flake8 is run. Wrap the docstring, mock context, assertions, and proxy test context across lines.</comment>

<file context>
@@ -26,13 +37,23 @@ async def counting_connect_tcp(*args, **kwargs):
         return len(attempts)
 
+    def build_client(self, config):
+        """Return the REST client, the transport kwargs (None if no custom transport) and the client kwargs."""
+        rest = RESTClientObject(config)
+        with patch("petstore_api.rest.httpx2.AsyncHTTPTransport", wraps=httpx2.AsyncHTTPTransport) as transport, \
</file context>

@@ -0,0 +1,104 @@
"""Configuration.retries is passed to httpx's transport retries, for direct connections."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: Several added lines exceed this sample’s configured 99-character flake8 limit, causing lint failures when flake8 runs. Wrap the helper, patch, assertion, and context-manager lines to keep each line within the configured limit.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At samples/openapi3/client/petstore/python-httpx/tests/test_retries.py, line 48:

<comment>Several added lines exceed this sample’s configured 99-character flake8 limit, causing lint failures when flake8 runs. Wrap the helper, patch, assertion, and context-manager lines to keep each line within the configured limit.</comment>

<file context>
@@ -26,13 +37,23 @@ async def counting_connect_tcp(*args, **kwargs):
         return len(attempts)
 
+    def build_client(self, config):
+        """Return the REST client, the transport kwargs (None if no custom transport) and the client kwargs."""
+        rest = RESTClientObject(config)
+        with patch("petstore_api.rest.httpx.AsyncHTTPTransport", wraps=httpx.AsyncHTTPTransport) as transport, \
</file context>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG][PYTHON] httpx library ignores Configuration.retries

1 participant