[Bug] find_free_port() reports the last busy port as free when its scan window is exhausted
Checklist / 检查清单
- I have searched existing issues, and this is a new bug report. / 我已经搜索过现有的 issues,确认这是一个新的 bug report。
Bug Description / Bug 描述
swift.utils.find_free_port() returns a port that is not free when every bind attempt in
[start_port, start_port + retry) fails, and raises UnboundLocalError when that range is empty.
The function reuses its loop variable as the return value (swift/utils/utils.py:299-310 at dbc395ff):
for port in range(start_port, start_port + retry):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
try:
sock.bind(('', port))
port = sock.getsockname()[1]
break
except OSError:
pass
return portWhen no bind succeeds the break is never reached, so port still holds the last candidate that was
just proven busy, and that value is returned as though it were free. With retry <= 0 the loop body
never runs at all and return port reads an unbound local.
How to Reproduce / 如何复现
No GPU, model or network access is needed — only socket:
import socket
from swift.utils import find_free_port
BASE = 47110 # any window of free ports works, as long as it is fully occupied below
def occupy(count, base=BASE):
socks = []
for port in range(base, base + count):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', port))
s.listen(1)
socks.append(s)
return socks
socks = occupy(3)
try:
got = find_free_port(BASE, retry=3)
print('returned port =', got, '(candidates were', BASE, '..', BASE + 2, ')')
probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
probe.bind(('', got))
print('the returned port is free -> no defect')
except OSError as e:
print('the returned port is IN USE ->', type(e).__name__, e)
finally:
probe.close()
finally:
for s in socks:
s.close()
try:
find_free_port(BASE + 20, retry=0)
except Exception as e:
print('retry=0 raised', type(e).__name__, '->', e)Measured output on main @ dbc395ff (Windows 11, Python 3.12):
returned port = 47112 (candidates were 47110 .. 47112 )
the returned port is IN USE -> OSError [WinError 10048]
retry=0 raised UnboundLocalError -> cannot access local variable 'port' where it is not associated with a valueThe same reasoning applies on Linux: the returned value is the last candidate whose bind raised
EADDRINUSE.
Additional Information / 补充信息
Why it matters — both CLI entry points consume the return value as the server port with no further check:
swift/arguments/deploy_args.py:57:self.port = find_free_port(self.port)swift/arguments/app_args.py:50:self.server_port = find_free_port(self.server_port)
So a swift deploy / swift app whose configured port window is fully occupied is handed a busy port
and only fails later inside uvicorn/gradio with an "address already in use" error that no longer
mentions the port scan. swift/ray_utils/base.py:303 uses the default retry=100 path.
Expected behavior: socket.bind already signals an unusable port with OSError, so an exhausted scan
window should raise OSError naming the range instead of reporting a busy port as free — the same
shape the repository already uses for its private helper _find_free_port()
(swift/ray/megatron/checkpoint_engine/base.py:21), which returns inside the with block.
Prior art: PR #9870 ("fix(utils): report free port search exhaustion") proposed the same direction and was closed unmerged by its own author on 2026-08-12 with no maintainer review. This report is written from the reproduction above; that patch was not reused.
Disclosure: this issue was filed by an AI agent operating on the account of @Lesereingrape; the quoted output is measured, not illustrative.
Source: modelscope/ms-swift