Skip to content

[BUG CLIENT]: Connection leak: streaming requests that return an error status are never closed #532

Closed

Description

@ronnix

Python -VV

Python 3.13.13 (main, May  3 2026, 21:46:01) [Clang 21.0.0 (clang-2100.0.123.102)]

Pip Freeze

mistral-common==1.11.0
mistralai==2.3.2

Reproduction Steps

Fire ~20+ concurrent chat.stream_async calls on a single shared Mistral
client against an endpoint that returns errors (e.g. 429 rate limits, or any
4xx/5xx). After enough leaked connections accumulate, subsequent calls fail with
httpx.PoolTimeout. Creating a fresh client per call works around it (the leaked
connections are reclaimed when the whole client is garbage-collected).

Expected Behavior

The httpx pool is not exhausted.

Additional Context

Summary

When a streaming request (chat.stream_async, stream_async, etc.) receives an
error HTTP status, the SDK raises an exception (or retries) without closing
the underlying streaming httpx.Response
. The pooled connection stays checked
out forever. Under concurrency with a shared client, hitting enough 429s exhausts
the httpx connection pool and subsequent calls fail with httpx.PoolTimeout.

Affected versions

Confirmed identical from 2.3.2 through 2.4.5 — the Speakeasy-generated HTTP
layer is unchanged across these releases.

Root cause

For a streaming request, client.send(req, stream=True) returns a Response
that holds a connection from the pool until the body is fully consumed or
aclose() is called. Two code paths leak it on an error status:

  1. src/mistralai/client/basesdk.py — do_request_async: when the response
    status matches error_status_codes, it invokes the error hook and raises
    errors.SDKError("Unexpected error occurred", http_res). With stream=True,
    http_res is a live streaming response that is never aclose()d.

  2. src/mistralai/client/utils/retries.py — retry_async /
    retry_with_backoff_async:
    for a retryable status (429/500/502/503/504),
    the inner do_request raises TemporaryError(res); retry_with_backoff_async
    then sleeps and retries, dropping res (the open streaming response) without
    closing it. Each retried attempt leaks one connection.

The synchronous variants (retry / retry_with_backoff, do_request) have the
same problem.

Non-streaming requests are unaffected: with stream=False, httpx reads the
full body and releases the connection back to the pool.

Suggested Solutions

Close the streaming response before raising or retrying on an error status:

  • In do_request_async / do_request: when stream=True, await http_res.aclose()
    (resp. http_res.close()) before raising SDKError.
  • In retry_async / retry: close res before raising TemporaryError, or in
    the retry loop (retry_with_backoff_async / retry_with_backoff) before the
    next attempt.

Activity

  1. ronnix commented on May 20, 2026

    @ronnix
    Author

    Related : #509

  2. ferhimedamine commented on Jun 16, 2026

    @ferhimedamine

    Unclosed streaming requests on error are a common resource leak in HTTP client libraries — the connection stays open until the server closes it (or the process exits), which exhausts connection pools under load.

    The standard fix: in the streaming path, wrap the response body iteration in a try/finally that calls response.close() (or uses a context manager) even on error exit. This ensures the connection is returned to the pool regardless of how the streaming ended.

    For agent systems using Mistral for inference where the agent's memory layer makes concurrent requests alongside the streaming LLM call, connection pool exhaustion from this leak can cause memory API requests to queue up behind stuck streaming connections. Worth fixing before scaling to concurrent agents. For the memory side, dakera-deploy uses connection pooling internally so its REST API is resilient to this kind of upstream leak.

  3. tonydzi commented on Jul 28, 2026

    @tonydzi

    Still present on 2.8.0 (checked against main at 7749c84, today's SDK regen). Both paths @ronnix identified are unchanged:

    • src/mistralai/client/basesdk.py:305 (sync) and :387 (async) — raise errors.SDKError("Unexpected error occurred", http_res) with no close() / aclose(), and http_res came from client.send(req, stream=stream).
    • src/mistralai/client/utils/retries.py:142,147 (sync) and :186,191 (async) — raise TemporaryError(res) drops the open response; each retried attempt leaks one connection.

    One detail worth adding, because I think it explains why this has been hard to move rather than merely unattended: both files are Speakeasy-generated and carry DO NOT EDIT. A PR against either gets overwritten by the next chore: 🐝 Update SDK — one landed today — so the fix can't just live where the bug is.

    For the first path there's a way around that inside the hand-maintained zone. basesdk.py calls hooks.after_error(...) before it raises, and the hook receives the live httpx.Response. _hooks/registration.py is explicitly "generated once and then free to be modified", and the same mechanism already carries WorkflowStreamErrorHook from #596. So an after_error hook that closes a streaming response before the SDKError propagates would survive regeneration and needs no generator change.

    The retry path can't be reached that way: TemporaryError is raised inside utils.retry's own do_request, so intermediate responses never reach after_error — only the final one does. That half looks like it genuinely needs the generator template (or retry_connection_errors semantics) changed upstream, which is presumably your call and not something an outside PR can carry.

    Happy to put up the hook for the first path — it's small and testable, roughly in the shape of _hooks/stream_error_hook.py. I'd rather not send it uninvited into a repo where most of the tree is generated, so: useful, or would you rather fix both halves upstream in one go? Either answer is fine — just say which and I'll act on it or drop it.

  4. Nelson-PROIA commented on Sep 10, 2026

    @Nelson-PROIA
    Contributor

    Fixed in mistralai 2.10.0.

    The retry path now closes the response before backing off, so a retried 429/500/502/503/504 on a streaming call no longer strands a pooled connection:

    if isinstance(exception, TemporaryError):
        retry_after_ms = _parse_retry_after_ms_header(exception.response)
        if retry_after_ms is not None:
            exception.retry_after = retry_after_ms
        await exception.response.aclose()

    The sync variant calls close() in the same place. This came in with a code generator upgrade, so it applies across the whole generated surface rather than one method.

    Checked against a local server with max_connections=2. On 2.8.0, a streaming call retried on 429 holds one connection per attempt and the pool is exhausted by the fifth call with PoolTimeout. On 2.10.0 the same test leaves every connection available.

    On the second path in the original report: basesdk.py still has no close(), but its raise errors.SDKError("Unexpected error occurred", http_res) is not reachable in this SDK. An after_error hook is registered that returns the response, so do_request takes the if result is not None branch and falls through to the generated operation, which calls stream_to_text_async(http_res) before raising. Reading the body releases the connection. Verified with a non-retryable 400, which also leaves the pool clean.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions