Skip to content

Commit 1ab57ba

Browse files
committed
Remove redundant comments and improve port allocation
- Remove redundant 'Always call parent __exit__' comments - Fix return in finally blocks to avoid swallowing exceptions - Update port allocation to search entire valid range - Add validated timing benchmarks to port_utils.py Signed-off-by: Keiven Chang <[email protected]>
1 parent 909fb97 commit 1ab57ba

File tree

4 files changed

+25
-22
lines changed

4 files changed

+25
-22
lines changed

tests/conftest.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,7 @@ def pytest_runtestloop(session):
245245

246246
class EtcdServer(ManagedProcess):
247247
def __init__(self, request, port=2379, timeout=300):
248-
# Allocate free ports if port is None or 0
248+
# Allocate free ports if port is 0
249249
use_random_port = port == 0
250250
if use_random_port:
251251
# Need two ports: client port and peer port for parallel execution
@@ -314,14 +314,13 @@ def __exit__(self, exc_type, exc_val, exc_tb):
314314
free_ports(ports_to_release)
315315
except Exception as e:
316316
logging.warning(f"Failed to release EtcdServer port: {e}")
317-
finally:
318-
# Always call parent __exit__ to terminate the process
319-
return super().__exit__(exc_type, exc_val, exc_tb)
317+
318+
return super().__exit__(exc_type, exc_val, exc_tb)
320319

321320

322321
class NatsServer(ManagedProcess):
323322
def __init__(self, request, port=4222, timeout=300):
324-
# Allocate a free port if port is None or 0
323+
# Allocate a free port if port is 0
325324
use_random_port = port == 0
326325
if use_random_port:
327326
# Start from 4223 (nats-server default 4222 + 1)
@@ -356,9 +355,8 @@ def __exit__(self, exc_type, exc_val, exc_tb):
356355
free_port(self.port)
357356
except Exception as e:
358357
logging.warning(f"Failed to release NatsServer port: {e}")
359-
finally:
360-
# Always call parent __exit__ to terminate the process
361-
return super().__exit__(exc_type, exc_val, exc_tb)
358+
359+
return super().__exit__(exc_type, exc_val, exc_tb)
362360

363361

364362
class SharedManagedProcess:
@@ -502,7 +500,7 @@ def runtime_services(request):
502500

503501
@pytest.fixture()
504502
def runtime_services_dynamic_ports(request):
505-
"""Provide NATS and Etcd servers with truly dynamic ports.
503+
"""Provide NATS and Etcd servers with truly dynamic ports per test.
506504
507505
This fixture actually allocates dynamic ports by passing port=0 to the servers.
508506
It also sets the NATS_SERVER and ETCD_ENDPOINTS environment variables so that
@@ -515,14 +513,14 @@ def runtime_services_dynamic_ports(request):
515513
# Port cleanup is now handled in NatsServer and EtcdServer __exit__ methods
516514
with NatsServer(request, port=0) as nats_process:
517515
with EtcdServer(request, port=0) as etcd_process:
518-
# Set environment variables for the dynamic ports.
519-
# xdist (parallel execution) will launch isolated tests in a new process, so no need to worry about environment pollution.
516+
# Set environment variables for Rust/Python runtime to use. Note that xdist (parallel execution)
517+
# will launch isolated tests in a new process, so no need to worry about environment pollution.
520518
os.environ["NATS_SERVER"] = f"nats://localhost:{nats_process.port}"
521519
os.environ["ETCD_ENDPOINTS"] = f"http://localhost:{etcd_process.port}"
522520

523521
yield nats_process, etcd_process
524522

525-
# Clean up environment variables after test
523+
# No test should rely on these variables after the test, but clean up just in case.
526524
os.environ.pop("NATS_SERVER", None)
527525
os.environ.pop("ETCD_ENDPOINTS", None)
528526

tests/fault_tolerance/cancellation/test_sglang.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -161,9 +161,8 @@ def __exit__(self, exc_type, exc_val, exc_tb):
161161
free_port(self.system_port)
162162
except Exception as e:
163163
logging.warning(f"Failed to release SGLang worker port: {e}")
164-
finally:
165-
# Always call parent __exit__ to terminate the process
166-
return super().__exit__(exc_type, exc_val, exc_tb)
164+
165+
return super().__exit__(exc_type, exc_val, exc_tb)
167166

168167
def is_ready(self, response) -> bool:
169168
"""Check the health of the worker process"""

tests/fault_tolerance/migration/test_sglang.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -120,9 +120,8 @@ def __exit__(self, exc_type, exc_val, exc_tb):
120120
free_port(self.system_port)
121121
except Exception as e:
122122
logging.warning(f"Failed to release SGLang worker port: {e}")
123-
finally:
124-
# Always call parent __exit__ to terminate the process
125-
return super().__exit__(exc_type, exc_val, exc_tb)
123+
124+
return super().__exit__(exc_type, exc_val, exc_tb)
126125

127126
def is_ready(self, response) -> bool:
128127
"""Check the health of the worker process"""

tests/utils/port_utils.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,14 +64,20 @@ def allocate_free_ports(count: int, start_port: int) -> list[int]:
6464
6565
Port range is limited to i16 (30000-32767) due to Rust backend expecting i16.
6666
67+
Searches sequentially from start_port to _PORT_MAX. If not enough ports found,
68+
wraps to _PORT_MIN and continues searching.
69+
70+
Performance: Tested walking through 200 ports (100 bound, 100 free) in ~1ms.
71+
Worst case (searching entire 1024-32767 range): ~143ms.
72+
6773
Args:
6874
count: Number of unique ports to allocate
6975
start_port: Starting port number for allocation (required)
7076
7177
Returns:
72-
list[int]: List of available port numbers between start_port and 32767
78+
list[int]: List of available port numbers
7379
"""
74-
# Validate start_port is in valid i16 range
80+
# Validate start_port is in valid i16 range. Note that <1024 is reserved for system services (root only)
7581
if start_port < 1024 or start_port > _PORT_MAX:
7682
raise ValueError(
7783
f"start_port must be between 1024 and {_PORT_MAX}, got {start_port}"
@@ -101,9 +107,10 @@ def allocate_free_ports(count: int, start_port: int) -> list[int]:
101107
# Start searching from start_port
102108
current_port = start_port
103109

104-
# Try to find free ports
110+
# Try to find free ports - search entire available range
105111
attempts = 0
106-
max_attempts = count * 50
112+
# Max attempts: twice the available range to handle wraparound
113+
max_attempts = (_PORT_MAX - _PORT_MIN + 1) * 2
107114

108115
while len(ports) < count and attempts < max_attempts:
109116
attempts += 1

0 commit comments

Comments
 (0)