Range-support early exit leaves streamed download response open during retry
Description
When download_file(..., raise_accepts_ranges=True) finds Accept-Ranges: bytes, it raises HTTPRangeRequestSupportedError without closing its streamed response. The response remains live in the exception traceback while the caller handles the exception. In the actual _get_info_from_wheel path, that handler recursively retries a lazy-wheel request inside the except block.
The following reproduction runs the real download_file from the current checkout against a local server. It uses a deliberately small blocking Requests connection pool to make the unreleased connection observable; I have not reproduced a hang with Poetry's default non-blocking pool.
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from tempfile import TemporaryDirectory
from requests import Session
from requests.adapters import HTTPAdapter
from poetry.utils.download import download_file, HTTPRangeRequestSupportedError
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def do_GET(self):
self.send_response(200)
self.send_header("Content-Length", "1")
self.send_header("Accept-Ranges", "bytes")
self.end_headers()
self.wfile.write(b"x")
def log_message(self, *args):
pass
def handle(self):
try:
super().handle()
except ConnectionResetError:
pass
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
session = Session()
session.trust_env = False
session.mount("http://", HTTPAdapter(pool_connections=1, pool_maxsize=1, pool_block=True))
url = f"http://127.0.0.1:{server.server_port}/test.whl"
with TemporaryDirectory() as temp:
try:
download_file(url, Path(temp) / "test.whl", session=session, raise_accepts_ranges=True)
except HTTPRangeRequestSupportedError as error:
# Inspect the actual response retained by the download_file traceback.
frame = error.__traceback__.tb_next.tb_frame
response = frame.f_locals["downloader"]._response
done = threading.Event()
def followup():
with session.get(url, timeout=2) as result:
result.content
done.set()
thread = threading.Thread(target=followup, daemon=True)
thread.start()
print("response closed:", response.raw.closed)
print("followup finishes before response close:", done.wait(0.5))
response.close() # release the slot so the demonstration terminates
print("followup finishes after response close:", done.wait(2))
thread.join(2)
session.close()
server.shutdown()
server.server_close()
Output:
response closed: False
followup finishes before response close: False
followup finishes after response close: True
Expected: close the unused streamed response before raising, allowing a subsequent request to use its connection pool slot. This is a different branch from the streamed-response cleanup covered by #9899, which closes responses on HTTP errors and after content iteration; here the early range-support exception occurs before either.
Workarounds
Use solver.lazy-wheel = false to avoid this range-probing path, or avoid a blocking session with a single connection. The reproduction explicitly closes the response as a demonstration; applications should not need to inspect exception frames.
Environment
- Poetry source checkout:
d59ff3b47c5d70b5e4934db874e94ea78b98feb8(editable installation reports Poetry 2.5.1) - Python 3.11.0, macOS, Requests 2.34.2
- Local HTTP server, no package index or network access required for the reproduction.
- This is a direct utility-level reproduction. I have not reproduced a deadlock with a default
poetry installcommand.
Open/closed issues and PRs were searched for HTTPRangeRequestSupportedError, download response closing, and range support. Codex assisted with investigation and drafting.
Confirmed by reading the control flow: the raise happens while the streamed response is still open, and Python keeps the frame - and therefore the response object - alive as part of the exception's traceback. The recursion inside the except block then holds a second live connection while the first one is still attached to the exception being handled.
Two consequences beyond the leak: the connection stays checked out of the pool for as long as the traceback exists (which, in a retry loop, is the whole retry chain), and on a server that limits concurrent connections the retry can fail with a connection error that looks unrelated to the original one.
The fix is to close before raising:
if response.headers.get("Accept-Ranges") == "bytes":
response.close()
raise HTTPRangeRequestSupportedError(...)
or, better, make the whole body of download_file a with block so every exit path closes:
with self._get(url, stream=True) as response:
...
The second version also covers the timeout and the write-error paths, which have the same shape.
One detail worth keeping: if the caller needs the response object in the exception (to read headers), copy the values out before closing rather than passing the response itself - otherwise the traceback keeps it alive again.
Thanks for looking into the response lifetime and the other exit paths. The context-manager approach sounds worth considering alongside regression tests for the retry path and cleanup on errors.