Skip to content

Commit 6153551

Browse files
committed
test: Fix port 0 bug in atomic counter initialization
fetch_update returns the previous value, so the first caller got port 0 instead of the random base. Use compare_exchange for one-time init followed by fetch_add, which correctly returns the base port to the first caller. AI tools were used in preparing this commit.
1 parent 72f1764 commit 6153551

File tree

1 file changed

+8
-10
lines changed

1 file changed

+8
-10
lines changed

tests/common/mod.rs

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -276,19 +276,17 @@ pub(crate) fn random_storage_path() -> PathBuf {
276276

277277
static NEXT_PORT: AtomicU16 = AtomicU16::new(0);
278278

279+
fn init_base_port() {
280+
// Initialize once with a random base port. compare_exchange ensures only one thread wins.
281+
let base = rng().random_range(10000..50000u16);
282+
let _ = NEXT_PORT.compare_exchange(0, base, Ordering::Relaxed, Ordering::Relaxed);
283+
}
284+
279285
pub(crate) fn random_listening_addresses() -> Vec<SocketAddress> {
280286
// Use an atomic counter to avoid intra-process collisions between parallel tests.
281287
// The base port is randomized once per process to avoid inter-process collisions.
282-
let port = NEXT_PORT
283-
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |p| {
284-
if p == 0 {
285-
let base = rng().random_range(10000..50000u16);
286-
Some(base + 2)
287-
} else {
288-
Some(p + 2)
289-
}
290-
})
291-
.unwrap_or_else(|p| p);
288+
init_base_port();
289+
let port = NEXT_PORT.fetch_add(2, Ordering::Relaxed);
292290
vec![
293291
SocketAddress::TcpIpV4 { addr: [127, 0, 0, 1], port },
294292
SocketAddress::TcpIpV4 { addr: [127, 0, 0, 1], port: port + 1 },

0 commit comments

Comments
 (0)